【问题标题】:No such column on ordering by association count没有按关联计数排序的列
【发布时间】:2015-10-14 13:19:26
【问题描述】:

我在尝试按关联计数订购模型时遇到了一些问题。我正在使用的方法被描述为here,它可以在控制台中工作,每当我使用 byebug 暂停它时。其他时候它根本不执行 select 语句,只是尝试进行分组和排序。这是我的课:

class Course < ActiveRecord::Base

has_many :course_videos, foreign_key: :course_id
has_many :videos, through: :course_videos

scope :ordered_by_video_count, -> {
joins(:videos)
    .select("courses.*, count(videos.id) as video_count")
    .group("courses.id")
    .order("video_count desc")
}
end

我得到的确切错误是:

SQLite3::SQLException: no such column: video_count: SELECT COUNT(*) AS count_all, courses.id AS courses_id FROM "courses" INNER JOIN "course_videos" ON "course_videos"."course_id" = "courses"."id" INNER JOIN "videos" ON "videos"."id" = "course_videos"."video_id" GROUP BY courses.id  ORDER BY video_count desc

谢谢!

斯蒂芬

【问题讨论】:

  • 由于某种原因它不尊重as,您可以在sql错误SELECT COUNT(*) AS count_all中看到这一点。您可以将顺序更改为count_all 而不是video_count。如果不是,您将需要弄清楚为什么 as 不被尊重。也许尝试用引号括起来?我不使用 sqlite,但一个快速的谷歌显示教程有它们,我不确定 sqlite 是否需要它们,所以可能什么都不做。 .select("courses.*, count(videos.id) as 'video_count'")
  • @japed count_all 排序和引号都没有做任何事情。 SQLite 仅适用于开发环境,但 postgres 似乎也跳过了它。

标签: sql ruby-on-rails activerecord associations


【解决方案1】:

不确定是否有影响,但请尝试

.order(video_count: :desc)

这是我一直使用的语法。

【讨论】:

  • 实际上,问题在于您需要使用缓存计数器。也许看看这个:yerb.net/blog/2014/03/13/…
  • 虽然我确实可以使用它,但我很想知道为什么这个 SQL 不起作用,以便下次不会犯同样的错误。不过谢谢!而且 video_count: :desc 并没有改变它。 Rails 有时会忽略整个 select 语句。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多