Ask A Question

Notifications

You’re not receiving notifications from this thread.

Logic on nested forms/related tables

Simon Cooper asked in Databases

I'm trying to improve my modles for an existing scenario, but I just can't get my head around it. The situation is that I want to list a range of coffee's and include the country and region of the beans. A coffee could be made from a single roast, but it could also be a blend of two or more.

At the moment I have just one model roasts that simply has fields for country1 region1, country2 region2 etc. Although, I'm led to believe it would be better to have a seperate model for countries. However, 1) would I add region field to the country model, or 2) would I have another model for regions - With country has_many :regions, and region belongs_to :country?

Reply

Hi Simon, I think this is more complicated than it seems on the surface. My initial thought was that you are missing a location object. This Location object would be associated with the Roast class. So calling roast.locations would return something like this:

{ "US" => ["Northeast", "Southwest"], "England" => ["London"] }

I'd have the country and regions classes outline just like you'd mentioned where country has many regions and a region belongs to a country and use those associations to build the locations. The benefit to this, from my perspective, is that you could have one location associated with more than one roast.

I'd look at a couple of ways to model this with [1] making sure the associations all made sense [2] making sure I'm minimizing any repetative data in the database [3] looking at using scopes and includes to get all the appropriate data out of the database and [4] looking at potentially using a multi-transitive association(s) here.

Here are a few links that might help in your process:

Hope that helps and doesn't confuse things...

Reply

Hey Robert.

Thanks for the response. I've ended up just going with a triple nested form:

class Roast < ApplicationRecord
    has_many :countries
end

class Country < ApplicationRecord
    belongs_to :roast
    has_many :regions
end

class Region < ApplicationRecord
    belongs_to :country
end

This does allow me to show the countries and their regions (up to 3 times) for any given roast. Hopefully this gives me a better foundation for adding more sophistication to the Roast model as I move forwards.

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 82,464+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.