问题
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