title: Scope model values and count in a single query | Rails 5
body: <p>I have models as follows:</p>
  
  <pre><code>class QuestionResult
    belongs_to :test_result
    belongs_to :test
  
    scope :answered -&gt; { where("answered = ?",true) }
    scope :unanswered, -&gt; { where("answered IS NULL OR answered != ?",true) }
  end
  
  class TestResult
    belongs_to :test
    has_many :question_results
  end
  </code></pre>
  
  <p>Now I need these values:</p>
  
  <pre><code>test_result.question_results.answered.count
  test_result.question_results.unanswered.count
  test_result.review_questions.count
  </code></pre>
  
  <p><code>review_questions</code> is a column in <code>test_results</code> table. </p>
  
  <p>So I need the value of <code>count</code> of <code>review_questions</code> in the <code>test_results</code> table and values of the <code>counts</code> of <code>scopes</code>: <code>answered</code> and <code>unanswered</code> in the associated <code>question_results</code> table. </p>
  
  <p>There is no column <code>unanswered</code> in the <code>question_results</code> table. It is only a <code>scope</code> but there is a column with the name <code>answered</code>. </p>
  
  <p>At present, I am querying these values as shown above. </p>
  
  <p>Is there any way that I can do the same in a single query?</p>
  
  <p><strong>Update 1</strong></p>
  
  <p>I am able to combine the first two queries into a single query without using <code>scopes</code> in query as below: </p>
  
  <pre><code>test_result.question_results.group(:answered).count
  </code></pre>
  
  <p>How can I combine <code>test_result.review_questions.count</code> query into the updated query?</p>
  
  <p><strong>Update 2</strong></p>
  
  <pre><code>SELECT 
  test_results.id, 
  sum(if (question_results.answered = 1, 1, 0)) as answered, 
  sum(if (question_results.answered = 0 or question_results.answered is null, 1, 0)) as unanswered, 
  test_results.review_questions 
  FROM test_results 
  INNER JOIN question_results ON question_results.section_result_id = test_results.id 
  WHERE test_results.id = test.test_result.last.id;
  </code></pre>
  
  <p>This is the working <code>sql</code> query. What is its equivalent <code>rails activerecord</code> query?</p>