rails连接的连接(rails 2.3.5和ruby 1.8.7)

时间:2011-06-08 12:36:25

标签: ruby-on-rails activerecord join

我有

data_records,品牌和影响者

data_records有很多品牌 data_records有1个影响者

品牌通过brand_influencers协会拥有许多影响者,该协会有一个名为top(boolean)的属性。

这是我的模特:

class DataRecord < ActiveRecord::Base
  belongs_to :influencer
  has_and_belongs_to_many :brands
end

class Brand < ActiveRecord::Base
 has_and_belongs_to_many :data_records
end

class Influencer < ActiveRecord::Base
  has_many :brands_influencers
  has_many :brands, :through => :brands_influencers
end

class BrandsInfluencer < ActiveRecord::Base
  belongs_to :brand
  belongs_to :influencer
end

我想做一个查询来获取给定品牌的所有data_records,其中有影响力的品牌是顶级影响者(top = true)。

我需要从data_record模型开始,因为还有其他动态查询可以固定在这个查询上(这是一个典型的大过滤器类型屏幕)。

所以我的问题是,是否有可能加入一个连接的实现。我已经使用了连接品牌并且它工作正常,但我无法找到加入brand_influencers关系的方法

感谢 乔尔

3 个答案:

答案 0 :(得分:4)

它的rails 2.3.5版本是,

DataRecord.find :all, :conditions => ['brands.name = ? AND influencers.top = ?', 'name', true], :joins => {:brands => :influencers}

我认为有一个品牌的名称,你正在寻找品牌名称。你需要像这样更改Brand

class Brand < ActiveRecord::Base
    has_and_belongs_to_many :data_records
    has_and_belongs_to_many :influencers
end

答案 1 :(得分:0)

听起来像是要使用

has_many :foos, :through=>:bar

has_one :foo, :through=>:bar

试试这个:

class DataRecord < ActiveRecord::Base
  # how does this relate to the other models?
end

class Brand < ActiveRecord::Base
 has_and_belongs_to_many :influencers
end

class Influencer < ActiveRecord::Base
  has_and_belongs_to_many :brands
end

class BrandsInfluencers < ActiveRecord::Base
  # notice the name change in this class (pluralization)
  belongs_to :brand
  belongs_to :influencer
end

答案 2 :(得分:0)

您可以从另一个join获取where并在DataRecord.joins(:influencers => {:brand_influencers}, :brands). where(:brands => {:id => 123}). where(:brands => {:brand_influencers => {:top => true}}) 中引用它们:

DataRecord.joins(:influencers => {:brand_influencers}, :brands).
  conditions(:brands => {:id => 123}). 
  conditions(:brands => {:brand_influencers => {:top => true}})

我很确定它在2.3.x中的工作方式类似。试试这个:

{{1}}

我建议您逐位构建关系并检查正在生成的SQL。祝你好运!