I do not think you can do this purely in a single query. At least not without writing pure sql.
But try to find a good solution in ActiveRecord
First of all, try removing some of sql
UserAnswer.count(:conditions => ['u.anonymous = 0 AND q.id = ?', question_id], :joins => 'JOIN answers a ON user_answers.answer_id = a.id JOIN questions q ON q.id = a.question_id JOIN users u ON u.id = user_answers.user_id')
can be rewritten
UserAnswer.joins(:user).where(:users => {:anonymous => false})\
.joins(:answer => :question).where(:questions => {:id => question_id})\
.count
magic_scope
def total_answers(question_id)
magic_scope(question_id).count
end
def load_stats_total(question_id)
magic_scope(question_id).count(:group => "answers.correct")
end
def load_stats_answers(question_id)
magic_scope(question_id).count(:group => "answers.id")
end
, , total_answers load_stats_*.
ActiveRecord ,
def all_the_magic(question_id)
magic_scope(question_id).count(:group => ["answers.correct", "answers.id"])
end
, .
, .
, .