简体   繁体   中英

Rails 4: Show List of Items in third level associations

I have Following structure in my rails app.

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

I want to access to cities from the country model. eg @country.cities . Also, how can I get the country from city model? eg @city.country

Thanks,

Use through option in has_many and delegate for 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM