Ruby on rails RoR关联是否通过?
我有四个相互关联的模型,我现在的设置方式是,当我进入一个新的城市时,我必须选择一个县、地区和国家Ruby on rails RoR关联是否通过?,ruby-on-rails,associations,Ruby On Rails,Associations,我有四个相互关联的模型,我现在的设置方式是,当我进入一个新的城市时,我必须选择一个县、地区和国家 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
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
不确定这是否正确,我已经阅读了how: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
我认为这在很大程度上取决于您计划如何引用每个模型。在您拥有的设置中(
有许多
/属于
),您可以这样引用每个模型:
city = City.find("Los Angeles, CA")
city.country # US
city.county # Los Angeles County
city.region # CA
而在一个通过建立的关系中,你必须通过通过引用访问模型的亲属,正如他在文章中提到的那样
city.region.county.country # US
还请记住,这意味着如果引用模型的相对值,它将通过它自己的SQL查询加载。谢谢Will,我太复杂了。
city = City.find("Los Angeles, CA")
city.country # US
city.county # Los Angeles County
city.region # CA
city.region.county.country # US