1

I have the following models, each a related child of the previous one (I excluded other model methods and declarations for brevity):

class Course < ActiveRecord::Base 
  has_many :questions

  scope :most_answered, joins(:questions).order('questions.answers_count DESC') #this is the query causing issues  
end 

class Question < ActiveRecord::Base 
  belongs_to :course, :counter_cache => true
  has_many: :answers

end 

class Answer < ActiveRecord::Base 
  belongs_to :question, :counter_cache => true
end

Right now I only have one Course populated (so when I run in console Course.all.count, I get 1). The first Course currently has three questions populated, but when I run Course.most_answered.count (most_answered is my scope method written in Course as seen above), I get 3 as the result in console, which is incorrect. I have tried various iterations of the query, as well as consulting the Rails guide on queries, but can't seem to figure out what Im doing wrong. Thanks in advance.

daspianist
  • 5,336
  • 8
  • 50
  • 94

1 Answers1

3

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.

Sam Peacey
  • 5,964
  • 1
  • 25
  • 27
  • Thank you! The first part where you explained why it was causing the repetition was especially helpful. I copied the code and got an syntax error, which I added to the body of my question. Thanks again for your help. – daspianist Feb 04 '13 at 04:52
  • I tried making some progress by ensuring that the small stuff wasn't causing the error, such as changing from plural to singular, or taking out certain elements to see if it'd at least render the view. Unfortunately as I am very new to writing queries these things didn't help.. thanks again. – daspianist Feb 04 '13 at 05:05
  • 1
    I've updated the answer to clarify what I meant - the `...` was meant to represent the fields you'd need to add to the select clause. – Sam Peacey Feb 04 '13 at 05:23
  • Excellent, glad to hear it. :) – Sam Peacey Feb 04 '13 at 05:31