2010-04-08 64 views
0

我有四个模型是相互关联的,我现在设置的方式是我必须在进入一个新城市时选择一个县,地区和国家。通过或不通过RoR协会?

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 

不知道这是正确的,我已经阅读如何:通过作品,但我不知道这是否是最好的解决办法。

我是一名新手,虽然我没有为语法和事情如何工作而苦苦挣扎,但最好从最佳实践中获得意见,并从某些导轨向导中完成某些事情。

在此先感谢。

回答

1

你需要这样做吗?难道你不只是有

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 
+0

谢谢,威尔,我过于复杂。 – showFocus 2010-04-08 02:58:10

1

我认为这在很大程度上取决于你计划如何引用每个模型。在设置你(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参考访问模型的亲戚,如威尔提到在他的职位。

city.region.county.country # US 

还铭记保持这种Rails loads model relatives lazily,这意味着如果你参考模型的相对它是通过它自己的SQL查询装入。