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

本秂侑毒 提交于 2019-12-01 02:43:48

问题


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.


回答1:


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

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


来源:https://stackoverflow.com/questions/4629744/activerecord-syntax-for-finding-all-items-with-an-average-rating-of-x-or-greater

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