Rails:访问相隔几度的相关对象

时间:2014-05-29 10:06:37

标签: ruby-on-rails

我有以下型号:

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
  belongs_to :account
end

class Account < ActiveRecord::Base
  has_many :users
  has_many :spies
  has_many :public_listings, through: :spies
end

class Competitor < ActiveRecord::Base
  belongs_to :integration_platform
  belongs_to :account
  has_many :spies
end

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

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

class PublicListing < ActiveRecord::Base
  has_many :spy_relationships
end

我在做两件事时遇到了麻烦:

1)在控制器中,如何查找与任何给定用户关联的所有公共列表(通过他们的帐户&gt; spies&gt;间谍关系)?

2)当我拉出public_listings时,有没有办法确定他们与哪个竞争对手相关联并将其分配给PublicListing的属性(通过spy_relationship&gt; spy&gt;竞争对手)?

由于

2 个答案:

答案 0 :(得分:1)

  

1)如何查找与任何给定关联的所有PublicListings   用户?

如果使用频繁,我建议在public_listing和load association中创建和维护user_id。

或者使用嵌套的includes并在单个查询中获取它们

u = User.includes({:account=>{:spies=>{:spy_relationships=>:public_listing}}}).where("id=1")

并照常访问

pl = u.account.spies.collect{|x| x.spy_relationships}.collect{|x| x.public_listing}
  

2)确定与哪个竞争对手相关的任何方式

照常收集

comps = pl.spy_relationships.collect{|x| x.spy}.collect{|x| x.competitor}
  

3)将其分配给PublicListing的属性

您需要使用虚拟属性。请检查此link

将模型更改为

   class PublicListing < ActiveRecord::Base
     attr_accessor :store
     has_many :spy_relationships
   end

   PublicListing.last.store = ## What ever you want ##

答案 1 :(得分:0)

1)在控制器中,如何查找与任何给定用户关联的所有公共列表(通过他们的帐户&gt; spies&gt;间谍关系)?

只是猜测,但您可以添加到您的用户模型

has_many :public_listings, through: :account

然后你可以做

User.find(x).public_listings

2)当我拉出public_listings时,有没有办法确定他们与哪个竞争对手相关联并将其分配给PublicListing的一个属性(通过spy_relationship&gt; spy&gt;竞争对手)?

在您的公开列表模型中,添加:

 has_many :spies, through: :spy_relationships
 has_many :competitors, through: :spies

然后你可以做这样的事情..

PublicListing.find(x).competitors.where(type_of_competitor_attribute: "is_this")