首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rails 7高级搜索链

Rails 7高级搜索链
EN

Stack Overflow用户
提问于 2022-11-29 22:02:05
回答 1查看 29关注 0票数 0

我想设置一个Rails资源的高级搜索(即产品),在这里我可以执行积极和消极的搜索。例如:

  • 产品是一款手机
  • 产品不是由苹果制造的
  • 产品是在过去16个月里生产的

我可以将多个参数传递给一个页面,但是有什么方法可以链接查询吗?

代码语言:javascript
复制
@results = Product.where("lower(type) LIKE ?", "%#{search_term.downcase}%").where(....

我想使用where和where.not的组合:

代码语言:javascript
复制
  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 where#ProductsController:0x00000000ac58

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-11-30 01:24:08

你可以像这样连锁where

代码语言:javascript
复制
Product.
  where(type: "phone").
  where.not(factory: "Apple").
  where(manufactered_at: 16.months.ago..)

rails 7还引入了invert_where (它反转了之前的所有condtions ),所以您可以

代码语言:javascript
复制
Product.
  where(factory: "Apple").invert_where.
  where(type: "phone").
  where(manufactered_at: 16.months.ago..)

您可以使用范围。

代码语言:javascript
复制
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)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74620691

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档