[英]RoR associations through or not through?
我有四个相互关联的模型,目前设置的方式是进入新城市时必须选择一个县,地区和国家。
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
在关联中使用:through
符号会更好吗? 所以我可以说这个城市:
has_one :country, :through => :region
不确定这是否正确,我已经阅读了:through的工作原理,但是不确定这是否是最佳解决方案。
我是一个新手,虽然我在语法和工作方式上不作任何努力,但最好还是从一些Rails向导那里获得有关最佳做法和方法的意见!
提前致谢。
您需要这样做吗? 你能不能只有
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
然后,如果您要查找城市的国家/地区,便可以
my_city = City.last
my_country = my_city.county.reguion.country
我认为这很大程度上取决于您参考每个模型的计划。 在您拥有的设置中( has_many
/ belongs_to
),您可以像这样引用每个模型:
city = City.find("Los Angeles, CA")
city.country # US
city.county # Los Angeles County
city.region # CA
而在has_many => through
关系中,您将被迫通过through
引用访问模型的亲戚,就像Will在他的帖子中提到的那样。
city.region.county.country # US
还请记住, Rails延迟加载模型相对对象 ,这意味着,如果您引用模型的相对对象,则会通过其自身的SQL查询来加载。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.