has_many / belongs_to associations in RoR
I've read the guide on associations but I feel like I'm still not
completely comprehending so I want to ask a couple of questions just to be
sure. Let's say I am making an app that will, among other things, list
large cities all over the world. I would plan on having a view that starts
at continent level and can be filtered down. So I would start with a
Continent model. And then a Country model. Now, within the Continent model
I would define an association as has_many :countries. And in the Country
model I would use belongs_to :continents. That much I grasp. So my next
model would be a model for states / province. Let's just call it Province
since that is more common throughout the world. So now I have my Province
model, and I would use belongs_to :country. And likewise Countries would
have has_many :provinces. My first question is, how do I describe the
association between Province and Continent? Has_many through describes
associations where both models have many. A Province only has one
Continent. Has_one through describes a relationship between objects that
have a one to one relationship via a third object. Again, this isn't the
case because a Continent will have many Provinces. So that is my primary
question.. how to describe relationships that exist in a one to many
through context. My second question would be just asking for tips on
writing the migrations for this in a situation where I add another layer,
say County, later on. But the main problem is just understand how to
express the relationships I described. Or if they even need to be
expressed.
Can I get the Document Links you are referring to? I have not been able to give an exact answer because I want to better understand the problem you are talking about.
ReplyDelete