如何使用两种不同模型的where方法?

时间:2015-11-12 00:27:05

标签: ruby-on-rails activerecord rails-activerecord where active-record-query

Hello Guys我有一个问题, 例如,我有一个模型Product :title, :description, :category_id。产品belongs_to :category 我的模型Category:name。并has_many :products

我正在尝试使用该方法的范围。我试着举例Product.where(category_id: 2)并且我拥有以id = 2保存的所有产品。 但我的问题是,如果我想在使用category.name: 'some_category'的条款中加入。我该怎么办?

4 个答案:

答案 0 :(得分:2)

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

使用string_or_array_of_names作为您的变量

答案 1 :(得分:0)

您可以使用joinsreferences

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

答案 2 :(得分: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")

答案 3 :(得分:0)

我找到了我想要做的最佳答案,并知道我想在这里分享,首先我安装gem has_scope

然后在我的产品模型中,我做了这个范围:

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

然后在products_controller中我把:

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链接时,它将显示在导航器/ contact?category = 1中,然后不会显示按我想要的方式过滤的产品。

然后解决此问题的解决方案是:

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

每次点击都会显示完美,非常简单和练习。感谢他们的帮助!