小编eda*_*edl的帖子

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 …

ruby-on-rails ruby-on-rails-6

3
推荐指数
1
解决办法
2103
查看次数

错误:别名中存在“ pitch_count”列时不存在

我在Rails 5中运行以下查询,目的是寻找音高最高的用户:

User
  .select("users.*, COUNT(user_id) as pitch_count")
  .unscoped
  .joins("LEFT JOIN pitches AS pitches ON pitches.user_id = users.id")
  .group("pitch.user_id")
  .order("pitch_count DESC")
  .limit(5)
Run Code Online (Sandbox Code Playgroud)

但是我得到了错误:

Caused by PG::UndefinedColumn: ERROR:  column "pitch_count" does not exist
Run Code Online (Sandbox Code Playgroud)

为什么查询不能按pitch_count排序?

postgresql ruby-on-rails

2
推荐指数
1
解决办法
95
查看次数