Rails 5:按created_at和updated_at排序

时间:2019-04-25 12:30:23

标签: ruby-on-rails ruby

使用以下代码,我订购的是最后创建或更新的产品:

@products = Product.where(:id=> @account.id).order('greatest(created_at, updated_at) desc').page(params[:page]).per(12)

它工作正常,但是由于我在控制台中收到以下消息,所以我想知道是否有更好的方法来实现上述目的?

DEPRECATION WARNING: Dangerous query method (method whose arguments 
are used as raw SQL) called with non-attribute argument(s): 
"greatest(created_at, updated_at) desc". Non-attribute arguments will
be disallowed in Rails 6.0. This method should not be called with 
user-provided values, such as request parameters or model attributes.
Known-safe values can be passed by wrapping them in Arel.sql().

1 个答案:

答案 0 :(得分:0)

将其包装在Arel.sql电话中,作为弃用消息提示:

@products = Product.where(:id=> @account.id).order(Arel.sql('greatest(created_at, updated_at) desc')).page(params[:page]).per(12)

如果好奇,请查看this issue in rails repo。有原始实现的链接以及实现的原因