2016-12-29 2 views
0

나는 내 레일 앱에서 다음과 같은 구조를 가지고 있습니다.레일 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

감사합니다,

답변

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

관련 문제