【问题标题】:How to use the where method with two different models?如何在两个不同的模型中使用 where 方法?
【发布时间】:2015-11-12 00:27:04
【问题描述】:

大家好,我有一个问题, 例如我有一个模特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' 的子句。我该怎么办?

【问题讨论】:

  • 未经测试,但请尝试Product.joins(:category).where(category: { name: "A Category Name"})。或者,Category.find_by(name: "A Category Name").products.

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


【解决方案1】:
Product.joins(:category).where(categories: { name: string_or_array_of_names })

使用string_or_array_of_names 作为变量

【讨论】:

  • 我很高兴它成功了!请记住接受答案。
  • 还有其他事情现在我的范围工作了我想在用户点击导航栏上的下拉菜单按钮时显示使用范围过滤的产品。怎么可能?
  • 您可以使用 ajax 提交包含下拉列表的表单。然后在 ajax 响应中你可以编辑页面。
【解决方案2】:

您可以使用joinsreferences

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

【讨论】:

  • 我在 Rails 控制台上遇到了一个错误:ArgumentError: 范围主体需要可调用。
【解决方案3】:
#app/models/product.rb
class Product < ActiveRecord::Base
   scope :by_category, ->(name) { joins(:category).where(categories: {name: name}) }
end

这将允许您调用:

@cars = Product.by_category("cars")

【讨论】:

  • 我试试这个,我得到一个错误:>> @z = Product.by_category("azeite") Product Load (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" = "products "."category_id" WHERE "category"."name" = ?
  • 我认为where 应该是categories。另外,你是如何传递你的变量的?
【解决方案4】:

我找到了我想做的事情的最佳答案,并且知道我想在这里分享,首先我安装了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>

而且每次点击都会完美显示,非常简单和练习。谢谢各位帮我!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-23
    • 1970-01-01
    • 2014-09-22
    • 1970-01-01
    • 1970-01-01
    • 2022-08-15
    相关资源
    最近更新 更多