2016-12-29 13 views
0

私は自分のレールアプリで次の構造を持っています。Rails 4:第3レベルのアソシエーションのアイテムのリストを表示

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。 また、都市モデルから国を取得するにはどうすればよいですか? 例えば@city.country

おかげで、belongs_toのためにhas_manyとデリゲートでオプションを使用して

答えて

5

用途:

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

関連する問題