2015-04-06 41 views
0

我有一個大型的評估表,在該表中有幾個帶有數字分數的整數列。我試圖刪除一些N + 1迭代來加速我的應用程序。在ActiveRecord查詢中引入自定義SELECT子句

我可以生成原始SQL此查詢收集所有得分

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' 

的當我執行此查詢有:

$> ActiveRecord::Base.connection.execute(query) 
=> #<PG::Result:0x007fc9e7e541e8 status=PGRES_TUPLES_OK ntuples=1 nfields=55 cmd_tuples=1> 

我得到正確的結果:

ActiveRecord::Base.connection.execute(query).first.values 
=> ["2400", "458", "3343", "1021", "93", "2352", "455", "3119", "1174", "150", "2378", "357", "2976", "1357", "181", "2042", "258", "3024", "1646", "280", "1274", "193", "3907", "1704", "172", "799", "93", "4593", "1670", "95", "1759", "361", "2542", "947", "69", "21", "100", "81", "42", "38", "8", "32", "51", "78", "112", "19", "119", "72", "43", "29", "0", "0", "0", "0", "0"] 

我想執行此相同的查詢,但不是整個表。我希望能夠鏈成一個ActiveRecord的查詢,例如:

Assessment.where(selection_attribute: 1038).select(query_without_select_keyword_or_from_clause) 

ActiveRecord::StatementInvalid: PG::GroupingError: ERROR: column "assessments.id" must appear in the GROUP BY clause or be used in an aggregate function 

,並把它給我同樣的樣的結果,但在子集。我天真的努力(例如我的例子中的.select(query)調用)失敗了,我甚至不知道如何處理這個。

我碰到了一面牆,我很感激任何指導,甚至在如何制定解決方案的搜索。謝謝。

回答

0

好吧,這很簡單。使用.first是個問題。我想這是因爲沒有查詢返回的模型記錄。如果我直接解決結果的0索引,我可以得到我的所有分數。

所以此代碼的工作:

query = 
     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(', ') 

Assessment.where(selection_attribute: 1038).select(query)[0] 
=> #<Assessment id: nil> 

Assessment.where(selection_attribute: 1038).select(query)[0].first_attribute_score_1 
=> 3