2016-12-29 91 views
0

我的Rails應用程序中有以下結構。Rails 4:顯示第三級關聯中的項目列表

class Country < ActiveRecord::Base 
    has_many :states 
end 

class State < ActiveRecord::Base 
    has_many :cities 
    belongs_to :country 
end 

class City < ActiveRecord::Base 
    belongs_to :state 
end 

我想從國家模式訪問城市。 例如@country.cities。 另外,如何從城市模型中獲取國家? e.g @city.country

感謝,

回答

5

使用通過的has_many選項,並委派belongs_to的:

class Country < ActiveRecord::Base 
    has_many :states 
    has_many :cities, through: :states 
end 

class State < ActiveRecord::Base 
    has_many :cities 
    belongs_to :country 
end 

class City < ActiveRecord::Base 
    belongs_to :state 
    delegate :country, to: :state 
end 
+0

感謝。有效。 – StarWars

+0

@StarWars如果此答案解決您的問題,而不是將其標記爲已接受 – Hizqeel