按计数排序 Rails 6

Order by count in Rails 6

RuleCategory 有很多规则。我想按规则数量列出 RuleCategories。

我正在使用 Rails 5.2.1,但是当我进行分组并尝试按计数 (*) 排序时,我收到一条错误消息,因为我使用的是原始 SQL。

RuleCategory.joins(:rules).where(rules: {edit_status: [Rule::EDIT_STATUS_SYNCHED, Rule::EDIT_STATUS_EDIT]})
.group(:category).order('count(*)').limit(5).pluck(:category, :id).to_a

DEPRECATION WARNING: Dangerous query method (method whose arguments are used as raw SQL)
called with non-attribute argument(s): "count(*)". 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(). (called from irb_binding at (irb):2)

如何在订单子句中加入计数语句?

rails 中的弃用警告写得非常好。他们通常会告诉您如何修复它们。看警告的最后一行:

Known-safe values can be passed by wrapping them in Arel.sql(). (called from irb_binding at (irb):2)

它告诉你使用 Arel.sql() 函数,如果你确定你的代码是正确的并且直接在 order 中使用原始 SQL SQL 子句。应按以下方式使用:

RuleCategory
  .joins(:rules)
  .where(rules: {edit_status: [Rule::EDIT_STATUS_SYNCHED, Rule::EDIT_STATUS_EDIT]})
  .group(:category)
  .order(Arel.sql('count(*)'))
  .limit(5)
  .pluck(:category, :id).to_a

(为便于阅读而添加的新行)

查看带有 order 子句的部分:

  .order(Arel.sql('count(*)'))

这应该可以修复弃用警告。