RoR associations through or not through?
I have four models that are related to one another, the way I have it setup at the moment is I have to select a county, region and country when entering a new city.
class Country < ActiveRecord::Base
has_many :regions
has_many :counties
has_many :cities
end
class Region < ActiveRecord::Base
has_one :country
has_many :counties
has_many :cities
end
class County < ActiveRecord::Base
has_one :country
has_one :region
has_many :cities
end
class City < ActiveRecord::Base
has_one :country
has_one :region
has_one :county
end
Would it be better to use the :through
symbol in the association? So I could say the city:
has_one :country, :through => :region
Not sure if this is correct, I have read how :through works but I'm not sure if this is the best solution.
I am a newbie and while I'm not struggling with the syntax and how things work, it would be good to get opinions on best practices and the way things should be done from some rails wizards!
Thanks in 开发者_运维知识库advance.
Do you need to do that? Could you not just have
class Country < ActiveRecord::Base
has_many :regions
end
class Region < ActiveRecord::Base
belongs_to :country
has_many :counties
end
class County < ActiveRecord::Base
belongs_to :region
has_many :cities
end
class City < ActiveRecord::Base
belongs_to :county
end
Then if you want to find the country of a city you would do
my_city = City.last
my_country = my_city.county.reguion.country
I think this largely depends on how you plan on referencing each model. In the setup you have (has_many
/belongs_to
), you'd reference each model like so:
city = City.find("Los Angeles, CA")
city.country # US
city.county # Los Angeles County
city.region # CA
Whereas in a has_many => through
relationship, you're forced to access a model's relatives through the through
reference, as Will mentioned in his post.
city.region.county.country # US
Also keep in mind that Rails loads model relatives lazily, meaning if you reference a model's relative it is loaded through it's own SQL query.
精彩评论