Ruby on rails 轨道:访问相隔几度的关联对象
我有以下型号:Ruby on rails 轨道:访问相隔几度的关联对象,ruby-on-rails,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
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
class用户
我在做两件事时遇到困难:
1) 在控制器中,如何查找与任何给定用户关联的所有PublicListings(通过他们的帐户>间谍>间谍关系)
2) 当我拉公共列表时,有没有办法确定他们与哪个竞争对手关联,并将其分配给公共列表的属性(通过spy_relationship>spy>competitor)
谢谢
1) 如何查找与任何给定项目相关的所有PublicListings
用户
如果使用频繁,我建议在public_listing and load association中创建并维护一个用户id
或者使用嵌套查询并在单个查询中获取它们
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}
comps = pl.spy_relationships.collect{|x| x.spy}.collect{|x| x.competitor}
2) 有没有办法确定他们与哪个竞争对手有关联
照常收取
pl = u.account.spies.collect{|x| x.spy_relationships}.collect{|x| x.public_listing}
comps = pl.spy_relationships.collect{|x| x.spy}.collect{|x| x.competitor}
3) 将其分配给PublicListing的一个属性
您需要使用虚拟属性。检查这个
改变你的模型
class PublicListing < ActiveRecord::Base
attr_accessor :store
has_many :spy_relationships
end
PublicListing.last.store = ## What ever you want ##
class PublicListing
1)在控制器中,我如何查找与任何给定用户关联的所有公共列表(通过他们的帐户>间谍>间谍关系)
只是猜测,但您可以添加到您的用户模型中
has_many :public_listings, through: :account
那你就可以了
User.find(x).public_listings
2) 当我拉公共列表时,有没有办法确定他们与哪个竞争对手关联,并将其分配给公共列表的属性(通过spy_relationship>spy>competitor)
在PublicListing模型中,添加:
has_many :spies, through: :spy_relationships
has_many :competitors, through: :spies
然后你可以做这样的事情
PublicListing.find(x).competitors.where(type_of_competitor_attribute: "is_this")
我绝对不会使用
collect
语句,因为它们对您的数据库非常昂贵,而且不具有任何可扩展性。是的,但是使用includes
可以显著降低数据库检索成本。