Incorporating Custom SELECT clause in ActiveRecord query
问题 I have a large table of assessments, in that table there are several integer columns with numerical scores. I am trying to remove some N+1 iteration to speed up my application. I can generate this query in raw SQL to gather all of the scores query = 'SELECT ' + Assessment.rating_attributes.collect{|attribute| 1.upto(5).collect do |i| %Q{SUM(CASE WHEN #{attribute.to_s} = #{i} then 1 else 0 end) as #{attribute}_score_#{i}} end }.join(', ') + ' FROM assessments' When I execute this query with: $