Search code examples
ruby-on-railsruby-on-rails-4associations

Query/scope not including unsaved records in association


Scenario: I have a quiz type setup where Questions have many Answers and also have a Response provided by the user (omitted). A response has a selected attribute to indicate the user's choice and a correct? method that compares selected with the correct_answer.

Code: is here in this GitHub repo, along with seed data. Quick links to:

Problem: I want to return all responses for a question that are correct however, unsaved records are not included.

I've tried a couple of different ways, as you'll see in the code including scope, question.correct_responses and also inverse_of (which I've read is supposed to be automatic now) - but to no avail.

Basically, I'm expecting following code to return 1, not 0.

q=Question.first
r=q.responses.build
r.selected = q.correct_answer
q.responses.correct.size # => 0??!  wtf man!?

Your assistance is greatly appreciated.


Solution

  • When you use a scope you're going to the database.

    Since you aren't saving the response, you don't want to go to the database. Instead, you should use something like the line below, which will select all of the question's "correct" responses and then count them.

    q.responses.select { |r| r.correct? }.size
    

    EDIT: or the short syntax for select:

    q.responses.select(&:correct?).size