2010-04-08 66 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查詢裝入。