Query that joins child model results item erroneously shown multiple times

佐手、 提交于 2019-12-08 18:18:27

From what I can gather, your most_answered scope is attempting to order by the sum of questions.answer_count.

As it is there is no sum, and since there are three answers for the first course, your join on to that table will produce three results.

What you will need to do is something like the following:

scope :most_answered, joins(:questions).order('questions.answers_count DESC')
  .select("courses.id, courses.name, ..., SUM(questions.answers_count) as answers_count")
  .group("courses.id, courses.name, ...")
  .order("answers_count DESC")

You'll need to explicitely specify the courses fields you want to select so that you can use them in the group by clause.

Edit:

Both places where I mention courses.id, courses.name, ... (in the select and the group), you'll need to replace this with the actual columns you want to select. Since this is a scope it would be best to select all fields in the courses table, but you will need to specify them individually.

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