0

你好,我有一個問題, 例如我有一個模型Product誰有 :title, :description, :category_id。而產品belongs_to :category 和我有一個Category誰有:name。和has_many :products如何在兩種不同的模型中使用where方法?

我想做一個範圍誰將使用的方法在哪裏。我嘗試例如Product.where(category_id: 2),我有所有保存id = 2的產品。 但我的問題是,如果我想在條款中使用category.name: 'some_category'。我能怎麼做?

+1

未經測試,但嘗試'Product.joins(:category).where(category:{name:「A Category Name」})'。或者,'Category.find_by(名稱:「類別名稱」).products'。 – Rog

回答

2
Product.joins(:category).where(categories: { name: string_or_array_of_names }) 

使用string_or_array_of_names爲您的變量

+0

這個工作很完美,謝謝你的約翰波拉德和你們所有人! – rld

+0

我很高興它的工作!請記住接受答案。 –

+0

現在我有了範圍工作,當用戶使用導航欄上的下拉菜單按鈕進行單擊時,我想要顯示使用範圍過濾的產品。它的可能性如何? – rld

0

您可以使用joinsreferences

Product.joins(:category).references(:category).where("categories.name = ?", "a name") 
+0

當我放置在滑軌控制檯上時,出現此錯誤: ArgumentError:範圍正文需要被調用。 – rld

0
#app/models/product.rb 
class Product < ActiveRecord::Base 
    scope :by_category, ->(name) { joins(:category).where(categories: {name: name}) } 
end 

這將允許您撥打:

@cars = Product.by_category("cars") 
+0

我試試這個,我得到一個錯誤:>> @z = Product.by_category(「azeite」) 產品負載(0.7ms)SELECT「products」。* FROM「products」INNER JOIN「categories」ON「categories」。 「id」=「products」。「category_id」WHERE「category」。「name」=? [[「name」,「azeite」]] SQLite3 :: SQLException:no such column:category.name:SELECT「products」。* FROM「products」INNER JOIN「categories」ON「categories」。「id」=「產品「。」category_id「WHERE」category「。」name「=? – rld

+0

我認爲'where'應該是'categories'。另外,你如何傳遞你的變量? –

0

我找到了我想要做一個最好的答案,知道我想在這裏分享,首先我安裝一個gem has_scope。在我把products_controller

scope :category, -> category_id {where(:category_id => category_id)} 

然後:

has_scope :category 

def index 
    @products = apply_scopes(Product).all 
end 

然後在我的導航欄,我把

然後在我的產品型號我做這個範圍此鏈接:

<li><%= link_to 'Oils', category: 1 %></li> 
<li><%= link_to 'Wines', category: 2 %></li> 

這是可能的只顯示這些類型的產品類別。 但是這有一個問題! 它將工作只是如果你首先點擊Products.path將顯示所有的產品,然後如果你點擊這些鏈接將正常工作。 但是,當我點擊Contact.path等其他鏈接,然後點擊Oils鏈接時,它將顯示在導航器/聯繫人?category = 1中,然後不會顯示像我想要的那樣過濾的產品。

那麼對於修復解決此問題是:

<li><%= link_to 'Azeites', '/products?category=1' %></li> 
<li><%= link_to 'Vinhos', '/products?category=2' %></li> 

而且你每次點擊時會顯示完美,非常簡單的做法。謝謝你們的幫助!

相關問題