Active Record has_many关系三层深吗?

Mic*_*dah 1 activerecord ruby-on-rails

class State < ActiveRecord::Base
  has_many :cities
end

class City < ActiveRecord::Base
  has_many :zipcodes
  belongs_to :state
end

class Zipcode < ActiveRecord::Base
  belongs_to :city
end
Run Code Online (Sandbox Code Playgroud)

当我尝试做:

State.first.cities.zipcodes
Run Code Online (Sandbox Code Playgroud)

我收到一个ActiveRecord::Associations::CollectionProxy错误.

有没有人知道如何使用has_many关系深入多层次?我确实使用该through:选项使这个工作,但无论如何不使用该through:选项吗?

Dmi*_*eev 5

你需要的是什么

像这样向你的城市类添加另一个关联子句

class State < ActiveRecord::Base
  has_many :cities
  has_many :zipcodes, through: :cities 
end
Run Code Online (Sandbox Code Playgroud)

然后你就可以打电话了

state.zipcodes
Run Code Online (Sandbox Code Playgroud)

这将返回给定州的所有邮政编码(通过相关城市)