2011-06-08 91 views
2

導軌聯接(軌道2.3.5和1.8.7紅寶石)

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模型開始,因爲還有其他動態查詢可以插入到此查詢中(這是一個典型的大型過濾器類型屏幕)。

所以我的問題,是否有可能加入一個連接realtionship。我已經使用連接品牌和它工作正常,但我不能想出一個辦法來湊brand_influencers關係

感謝 喬爾

+0

這將是更容易理解這一點,如果它是那麼有belongs_to的,的has_many,HAS_ONE等AR關係定義Ruby類。 – Teddy 2011-06-08 12:40:35

回答

4

導軌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 
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 
+0

嗨,我試圖找出如何編寫活動記錄查詢。 – Joelio 2011-06-08 14:23:32

0

你可以從另一個join和引用它們的where這樣的:

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

我敢肯定它的工作方式類似於在2.3.x.試試這個:

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

我建議你建立一點一點的關係並檢查正在生成的SQL。祝你好運!

+0

我認爲這正是我需要的,但我需要它的rails 2.3.5版本。 – Joelio 2012-03-27 11:41:17