Model.order() 不将任何内容传递给 rails order 函数



如果我遇到可能必须传递一些参数但如果它们不存在,我需要默认顺序的情况,调用类似 User.order() 的东西是否合法。还是有一些默认调用..

所以例如

# if the order_by exists I need to sort by that otherwise I need to get default results
order = params[:order_by]
@results = User.order(order)

如果您不知道会收到哪些参数,可以尝试使用以下代码:

@users = User.scoped # or any other default handler which returns ActiveRecord::Relation
@users = @users.where(name: params[:name]) if params[:name].present?
@users = @users.order(params[:order_by]) if params[:order_by].present?

最新更新