简体   繁体   中英

rails join of a join (rails 2.3.5 and ruby 1.8.7)

I have

data_records, brands and influencers

data_records have many brands data_records have 1 influencer

brands have many influencers via brand_influencers association which has an attribute called top (boolean).

here are my models:

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

I would like to do one query to get all data_records for a given brand where the influencers are in the brands top influencers (top = true).

I need to start on the data_record model because there are other dynamic queries that can be bolted on to this query (this is a typical big filter type screen).

So my question, is it possible to join in a realtionship of a join. I have used joins brands and it works fine, but I cant figure out a way to join in the brand_influencers relationship

thanks Joel

The rails 2.3.5 version of it is,

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

I am supposing there's a name for a brand and you're looking for the brand by name. And you need to change Brand like this:

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

Sounds like you want to use

has_many :foos, :through=>:bar

or

has_one :foo, :through=>:bar

Try this:

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

You can get a join from another and reference them in a where like this:

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

I'm pretty sure it works similarly in 2.3.x. Try this:

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

I would suggest you build up the relation bit by bit and check the SQL that's being generated. Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM