2012-10-03 53 views
8

我在Rails應用程序下面的模型Rails的where子句在兩個表

category => company => store 

商店有belongs_to公司,公司擁有belongs_to類別的關係。 現在我想使用商店對象的where方法來檢索同一類別內的所有商店。

我想有這樣的事情

@stores.nearbys(5).where("stores.company.category_id = xxx") 

有人可以給我一個提示這個

+0

@simone感謝突出代碼! – Martin

回答

17

嘗試加入與其中的連接表:

@stores.nearbys(5).joins(:company).where("companies.category_id = xxx") 

編輯:

爲了得到一個商店的類別你首先必須將類別方法委託給其公司:

class Store < ActiveRecord::Base 
belongs_to :company 

delegate :category, :to => :company 
end 

現在只需調用該方法在您的查詢:

@stores.nearbys(5).joins(:company).where("companies.category_id = ?", self.company.id) 
+0

太棒了!還有一個問題。我如何將商店的實際類別替換爲xxx,因爲它也可以通過相關公司訪問? – Martin

+0

我編輯了我的答案 - 希望它更有幫助 –

+0

謝謝。和simone的博客一起解決了我的問題。來自奧地利的所有最佳 – Martin

10

where支持嵌套的哈希值。

@stores.nearbys(5).where(:company => { :category_id => @category.id }, joins: company) 
+0

hi simone,與@ store.nearbys(5).where(company:{category_id},joins:company)我得到以下錯誤 - 語法錯誤,意外的'}',期待tASSOC ....哪裏(公司: category_id},joins:company) – Martin

+0

也許你沒有使用Ruby 1.9?我更新爲使用舊的語法。 –

+0

對不起,出現錯誤。我忘了'category_id'必須有一個值,在這種情況下'@ category.id'(確保修改代碼) –

-1

你可以試試這個

@category = Category.find xxx 

@store = @category.company.stores 
+0

那不是一個真正的選擇,因爲我有一個現有的存儲對象,我想是在同一類別中的所有商店... – Martin

+0

纔能有可能的話 另一個關係就像在商店 belongs_to的:類別,:通過=>:公司 –