Rails执行Order排序查询返回无效ArgumentError问题求助
问题根因
你定义了order_params私有方法用于给@order赋值,但没有在index方法执行前触发该方法,导致查询时@order取值为空,不符合排序参数规则抛出错误。你可以核对可正常运行的Characters控制器,大概率是配置了对应的before_action触发赋值逻辑。
修复方案
你可以任选以下两种方案之一修复:
- 方案1:新增
before_action配置,在执行index方法前触发参数赋值
class Api::V1::ProductionsController < ApplicationController # 新增此行 before_action :order_params, only: [:index] before_action :set_production, only: [:show, :update, :destroy] # 剩余原有代码保持不变 end
- 方案2:直接在
index方法内完成排序参数的获取,不需要额外的私有方法
def index order = params.fetch(:order, "ASC") @productions = apply_scopes(Production.limit(limit).offset(params[:offset])).order(created_at: order) render json: ProductionsRepresenter.new(@productions).as_json end
额外优化建议:建议增加参数合法性校验,避免用户传入非法的排序值导致报错,可将order_params调整为如下逻辑:
def order_params input_order = params.fetch(:order, "ASC").to_s.upcase @order = %w[ASC DESC].include?(input_order) ? input_order : "ASC" end
内容的提问来源于stack exchange,提问作者Ale Yanczuk
相关产品推荐
相关产品推荐

