【问题标题】:Rails 5: order by created_at and updated_at [duplicate]Rails 5:按 created_at 和 updated_at 排序 [重复]
【发布时间】:2019-04-25 12:30:23
【问题描述】:

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

@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().

【问题讨论】:

  • See
  • 感谢@Sebastian Palma,我将它包裹在Arel.sql 周围,消息不再出现
  • 您的 created_at 永远不应大于您的 updated_at,并且 ActiveRecord 始终设置一个 updated_at,因此您应该能够.order(updated_at: :desc)。我完全看不出有理由使用greatest,除非您在存储数据的方式上做了一些非常奇怪的事情。
  • @Nate 你说得有道理.. 使用.order(updated_at: :desc) 可能会更好。我没有做任何奇怪的事情,我只是想在顶部创建或更新最近创建或更新的任何记录。
  • @Dev 按 updated_at 降序排序就足够了。您的数据库进行排序应该会快一点,因为它不需要考虑 created_at 或找出哪个更大。

标签: ruby-on-rails ruby


【解决方案1】:

将其包装在 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。有原始实现的链接以及制作它的原因

【讨论】:

    猜你喜欢
    • 2017-05-26
    • 1970-01-01
    • 2010-10-18
    • 1970-01-01
    • 2012-05-15
    • 1970-01-01
    • 1970-01-01
    • 2011-07-17
    • 1970-01-01
    相关资源
    最近更新 更多