订单查询在Rails中返回无效的ArgumentError



我必须根据用户发送的参数(ASC, DESC)进行查询以订购数组,但它返回:

Started GET "/api/v1/productions" for 127.0.0.1 at 2021-10-22 23:24:18 -0300
Processing by Api::V1::ProductionsController#index as */*
Completed 500 Internal Server Error in 33ms (ActiveRecord: 0.0ms | Allocations: 5946)
ArgumentError (Direction "" is invalid. Valid directions are: [:asc, :desc, :ASC, :DESC, "asc", "desc", "ASC", "DESC"]):

app/controllers/api/v1/productions_controller.rb:9:in `index'

这是控制器:

class Api::V1::ProductionsController < ApplicationController
before_action :set_production, only: [:show, :update, :destroy]
MAX_PAGINATION_LIMIT = 10
has_scope :by_title
has_scope :by_genre
def index
@productions = (apply_scopes(Production.limit(limit).offset(params[:offset]))).order(created_at: @order)
render json: ProductionsRepresenter.new(@productions).as_json
end
def show
render json: ProductionRepresenter.new(@production).as_json
end 
def create
@production = Production.new(production_params)
if @production.save
render json: ProductionRepresenter.new(@production).as_json
else
render json: @production.errors, status: :unprocessable_entity
end
end
def update
if @production.update(production_params)
render json: ProductionRepresenter.new(@production).as_json, status: 200
else
render json: @production.errors, status: :unprocessable_entity
end
end
def destroy
@production.destroy
end

private
def limit
[params.fetch(:limit, MAX_PAGINATION_LIMIT).to_i].min
end
def production_params
params.permit(:title, :released_date, :score, :image, :production_type, {:character_ids => []}, {:genre_ids => []})
end
def set_production
@production = Production.find(params[:id])
end
def order_params
@order = params.fetch(:order, "ASC") 
end

end

我有另一个控制器叫做字符,这几乎是完全相同的,它正确排序。我尝试过很多事情,比如用@productions = (Production.all).order(created_at: @order)替换行(带或不带括号)。如果我字面上把字符串像order(created: 'asc')一样,它可以工作,但这不是我需要的,我不知道哪里出错了。

所以我将order_params更改为

def order
params.fetch(:order, "ASC") 
end

并将其替换为控制器

@productions = (apply_scopes(Production.limit(limit).offset(params[:offset]))).order(created_at: order)

有点效果,但我不确定这是否是解决问题的最佳方法。如果有,请告诉我