Rails 6 中按计数排序

Mar*_*rce 3 ruby-on-rails ruby-on-rails-6

RuleCategory 有很多规则。我想按 RuleCategories 拥有的规则数量列出它们。

我正在使用 Rails 5.2.1,但是当我执行 group by 并尝试按 count(*) 排序时,我收到一条错误消息,因为我使用的是原始 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)
Run Code Online (Sandbox Code Playgroud)

如何在 order 子句中添加 count 语句?

eda*_*edl 10

Rails 中的弃用警告写得非常好。他们通常会告诉您必须采取哪些措施来修复它们。查看警告的最后一行:

\n\n
\n

已知安全值可以通过将它们包装在 Arel.sql() 中来传递。(从 (irb):2 处的 irb_binding 调用)

\n
\n\n

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

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

(添加新行只是为了提高可读性)

\n\n

请参阅带有 \xc2\xa0clause 的部分order

\n\n
  .order(Arel.sql(\'count(*)\'))\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n