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> 

而且你每次点击时会显示完美,非常简单的做法。谢谢你们的帮助!

相关问题