我想设置一个Rails资源的高级搜索(即产品),在这里我可以执行积极和消极的搜索。例如:
我可以将多个参数传递给一个页面,但是有什么方法可以链接查询吗?
@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 where#ProductsController:0x00000000ac58
发布于 2022-11-30 01:24:08
你可以像这样连锁where
Product.
where(type: "phone").
where.not(factory: "Apple").
where(manufactered_at: 16.months.ago..)rails 7还引入了invert_where (它反转了之前的所有condtions ),所以您可以
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)https://stackoverflow.com/questions/74620691
复制相似问题