10
votes

An event has a column popularity and many keywords. A keyword has a category and a name. I am trying to order events by their popularity, but then only return the most popular event from each keyword name with the category "taxonomy".

Here's my query:

Event
  .order(:popularity)
  .joins(:keywords)
  .where(keywords: {category: "taxonomy"})
  .group("keywords.name")

But I am getting below error:

PG::GroupingError: ERROR: column "events.id" must appear in the GROUP BY clause or be used in an aggregate function

Where am I going wrong?

1
Postgres version ? some are suggesting to use 9.1Sajan

1 Answers

11
votes
Event
  .order(:popularity)
  .joins(:keywords)
  .group('events.id') # <======
  .where(keywords: { category: 'taxonomy' })
  .group('keywords.name')