Sta*_*ars 0 activerecord ruby-on-rails
我在我的rails应用程序中有以下结构.
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
Run Code Online (Sandbox Code Playgroud)
我想从乡村模式访问城市.例如@country.cities.另外,我怎样才能从城市模型中获得国家?例如@city.country
谢谢,
使用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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
182 次 |
| 最近记录: |