You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails 7资源高级搜索:链式Where正负查询实现报错求助

Rails Product资源正负搜索查询报错解决方法

报错原因

你在ProductsController里直接调用了where方法,但where是ActiveRecord模型(Product类)的类方法,控制器实例本身并没有这个方法,所以才会触发undefined method 'where' for #<ProductsController:0x0000000000ac58>错误。

正确实现方式

要基于Product模型来构建链式查询,以下是满足你需求的示例代码:
筛选手机品类、排除苹果品牌、查询近16个月生产的产品:

# 在ProductsController的index action中
def index
  @products = Product.where(category: '手机')
                     .where.not(brand: '苹果')
                     .where('production_date >= ?', 16.months.ago)
end

动态筛选扩展

如果需要根据前端传入的参数动态调整查询条件,可以这样拼接:

def index
  @products = Product.all

  # 动态添加品类筛选
  @products = @products.where(category: params[:category]) if params[:category].present?
  # 动态添加品牌排除
  @products = @products.where.not(brand: params[:exclude_brand]) if params[:exclude_brand].present?
  # 动态添加生产时间范围
  if params[:months_ago].present?
    @products = @products.where('production_date >= ?', params[:months_ago].to_i.months.ago)
  end
end

每个where/where.not调用都会返回一个ActiveRecord关系对象,因此可以持续链式调用,直到得到最终的查询结果。

内容的提问来源于stack exchange,提问作者Ken J

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 07:10:23