Rails/Postgres:列必须出现在GROUP BY子句中

Der*_*k J 4 postgresql ruby-on-rails

我有一个将用户加入帖子的范围,以便只获得具有可见帖子的用户.这适用于MySQL,但PG更严格,并抛出错误.

用户模型:

belongs_to :account

scope :have_posts, joins(:posts).where('posts.visible => true').group('users.id')
Run Code Online (Sandbox Code Playgroud)

控制器:

@account.users.have_posts.each do |user|
  # do stuff
end
Run Code Online (Sandbox Code Playgroud)

错误:

(PGError:错误:列"users.account_id"必须出现在GROUP BY子句中或用于聚合函数:SELECT"users".*FROM"users"INNER JOIN"posts"ON"posts"."user_id"= "users"."id"WHERE("users".account_id = 1)AND(recommendations.approved = true)GROUP BY users.id)

它抱怨来自调用的"users.account_id" @account.users(因为我显然不希望数据库中的所有用户).

知道怎么解决?

M. *_*her 6

问题是该GROUP BY条款.如果使用此选项,则无法选择任何非聚合字段,因此SELECT "users".* [...]不起作用.来自Postgres文档:

通常,如果对表进行分组,则除了在聚合表达式中之外,不能引用未在分组中使用的列.

这样的东西可能有用,虽然凌乱:

scope :have_posts, 
  joins('inner join (select user_id from posts where visible = true group by user_id) users_with_posts on users_with_posts.user_id=users.id')
Run Code Online (Sandbox Code Playgroud)

一种替代方法是使用像MAX或等聚合函数指定每个选定的字段MIN,但这可能会使范围更长,更不通用.