【问题标题】:Rails 7 Advanced Search Chain WhereRails 7 高级搜索链在哪里
【发布时间】:2022-12-09 07:33:49
【问题描述】:

我想设置 Rails 资源(即产品)的高级搜索,我可以在其中执行正面和负面搜索。例如:

  • 产品是手机
  • 产品不是 Apple 制造的
  • 产品是在过去 16 个月内制造的

我可以将多个参数传递给一个页面,但有没有办法链接查询?

@results = Product.where("lower(type) LIKE ?", "%#{search_term.downcase}%").where(....

我想结合使用 where 和 where.not:

  def search
    word1 = params[:word_1]
    word2 = params[:word_2]
    if word1.starts_with?('not')
      chain1 = where.not("lower(tags) LIKE ?", "%#{word1.downcase}%")
    else
      chain1 = where("lower(tags) LIKE ?", "%#{word1.downcase}%")
    end
    if word2.starts_with?('not')
      chain2 = where.not("lower(tags) LIKE ?", "%#{word2.downcase}%")
    else
      chain2 = where("lower(tags) LIKE ?", "%#{word2.downcase}%")
    end
    @products = Product.chain1.chain2
  end

但我收到以下错误:

undefined method #ProductsController 的位置:0x0000000000ac58`

【问题讨论】:

  • 你试过什么?可以链.where。这就是你要问的吗?我不清楚。
  • 还有where.not(...) 方法。
  • 是的,我问你是否可以链接 .where.where.not
  • 是的。您还可以制作预制范围,这些范围可以与 .where 和其他范围链接。

标签: ruby-on-rails activerecord


【解决方案1】:

你可以像这样链接where

Product.
  where(type: "phone").
  where.not(factory: "Apple").
  where(manufactered_at: 16.months.ago..)

rails 7 还引入了invert_where(它反转了它之前的所有条件)所以你可以

Product.
  where(factory: "Apple").invert_where.
  where(type: "phone").
  where(manufactered_at: 16.months.ago..)

您可以使用范围

class Product < ApplicationRecord
  scope :phone, -> where(type: "phone")
  scope :apple, -> where(factory: "Apple")
  scope :manufacatured_last, ->(period) { where(manufactered_at: period.ago..) }
end

Product.apple.invert_where.phone.manufacatured_last(16.months)

【讨论】:

    猜你喜欢
    • 2018-11-05
    • 2012-07-21
    • 1970-01-01
    • 2014-06-08
    • 2015-03-02
    • 2014-09-15
    • 1970-01-01
    • 2012-02-08
    • 1970-01-01
    相关资源
    最近更新 更多