Search code examples
sqlruby-on-railsactiverecordmysql-error-1111

ActiveRecord syntax for finding all items with an average rating of x or greater when using a join


I have two models in my rails application. Items and Reviews. Reviews belong to Item and Items has many Reviews.

The review model looks like this:

create_table "reviews", :force => true do |t|
  t.text     "comment"
  t.integer  "rating"
  t.integer  "reviewable_id"
  t.string   "reviewable_type"
  t.datetime "created_at"
  t.datetime "updated_at"
end

(Reviews are polymorphic so that's why they have a reviewable_id and a reviewable_type)

I'm trying to put together an ActiveRecord query that will allow me to select all Items that have an average rating of of say 80 or more.

I've tried a number of different variations on this which I thought would have worked

Item.joins(:reviews).where("avg(reviews.rating) > 80").group(:id)

however this results in the following error:

Error: Mysql2::Error: Invalid use of group function: SELECT `items`.* FROM `items` INNER JOIN `reviews` ON `reviews`.`reviewable_id` = `items`.`id` AND `reviews`.`reviewable_type` = 'Item' WHERE (avg(reviews.rating) > 80) GROUP BY id

If anyone can help it would be much appreciated.


Solution

  • You should put your condition in having instead of where. Meaning:

    Item.joins(:reviews).group("reviews.reviewable_id").having("avg(reviews.rating) > ?", 80)