Rails (PG::GroupingError: ERROR: column must appear in the GROUP BY clause or be used in an aggregate function

本小妞迷上赌 提交于 2021-01-29 13:49:32

问题


In my local this query work perfect with sqlite3

 def Event.most_like
   select("events.*, count(like_events.event_id) as likes_count")
   .joins(:like_events).group(:event_id).order("likes_count 
    DESC").limit(4)
 end

but i got some error when deploy heroku PG::GroupingError: ERROR: column "events.id" must appear in the GROUP BY clause or be used in an aggregate function

Can someone help me fix this?


回答1:


As the message, all fields in Select clause must appear in the GROUP BY or in aggregate function. In this case, you select all fields of Event so that the fields, which includes events.id, need to satisfy above requirement.

To fix that, I suggest to change function to select only event's id and likes_count as below:

def Event.most_like
  select("events.id, count(like_events.event_id) as likes_count").
  joins(:like_events).
  group('events.id').
  order("likes_count DESC").
  limit(4)
end

If you still need to get event records, you can fetch those records based on their ids.



来源:https://stackoverflow.com/questions/48369349/rails-pggroupingerror-error-column-must-appear-in-the-group-by-clause-or-be

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!