Rails:访问具有多个分离度的关联模型

时间:2014-05-28 16:53:55

标签: ruby-on-rails

我是rails的初学者,我有一个关于从另一个与几个分离度相关联的模型中访问一个模型的问题。

假设我有这些模型:

Account has_many Spies
Spy has many SpyRelationships and belongs to Account
SpyRelationship belongs to Listing and belongs to Spy

我如何设置关联,以便我可以简单地拉出与给定帐户关联的所有列表(通过其间谍和spyrelationship)?在正确设置这些关联之后,允许我这样做的代码是什么?

1 个答案:

答案 0 :(得分:1)

我猜你想通过间谍访问一个列表?

class Account < ActiveRecord::Base
  has_many :spies
  has_many :listings, through: :spies
end

class Spy < ActiveRecord::Base
  belongs_to :account
  has_many   :spy_relationships
  has_many   :listings, through: :spy_relationships
end

class SpyRelationship < ActiveRecord::Base
  belongs_to :listing
  belongs_to :spy
end

class Listing < ActiveRecord::Base
  has_many :spy_relationships
end