我正在使用以下模型构建 Rails 应用程序:
# vote.rb
class Vote < ApplicationRecord
belongs_to :person
belongs_to :show
scope :fulfilled, -> { where(fulfilled: true) }
scope :unfulfilled, -> { where(fulfilled: false) }
end
# person.rb
class Person < ApplicationRecord
has_many :votes, dependent: :destroy
def self.order_by_votes(show = nil)
count = 'nullif(votes.fulfilled, true)'
count = "case when votes.show_id = #{show.id} AND NOT votes.fulfilled then 1 else null end" if show
people = left_joins(:votes).group(:id).uniq!(:group)
people = people.select("people.*, COUNT(#{count}) AS people.vote_count")
people.order('people.vote_count DESC')
end
end
背后的想法order_by_votes
是按未完成的选票数量进行排序People
,要么计算所有选票,要么只计算与给定Show
.
当我对 SQLite 进行测试时,这似乎工作正常。但是当我切换到 Postgres 时,我得到了这个错误:
Error:
PeopleControllerIndexTest#test_should_get_previously_on_show:
ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR: column people.vote_count does not exist
LINE 1: ...s"."show_id" = $1 GROUP BY "people"."id" ORDER BY people.vot...
^
如果我使用 转储 SQL @people.to_sql
,这就是我得到的:
SELECT people.*, COUNT(nullif(votes.fulfilled, true)) AS people.vote_count FROM "people" LEFT OUTER JOIN "votes" ON "votes"."person_id" = "people"."id" GROUP BY "people "."id" 按 people.vote_count DESC 排序
为什么这在 Postgres 上失败但在 SQLite 上工作?我应该怎么做才能让它在 Postgres 上运行?
(PS:我用一个点命名了字段people.vote_count
,所以我可以在我的视图中访问它,而无需执行另一个 SQL 查询来实际查看视图中每个人的投票计数(不确定这是否有效)但我得到了即使我简单地命名该字段,也会出现同样的错误vote_count
。)
(PS2:我最近添加了.uniq!(:group)
因为 Rails 6.2 的一些弃用警告,但我找不到任何文档,所以我不确定我做对了,如果没有那部分,错误仍然存在。)