2012-05-13 30 views
2

從這個輸入:{ '聽力'=> 1}我需要生成該查詢如何在squeel中動態地處理where條件?

Score.joins(:target_disability).where{ (target_disabilities.name == 'hearing') & (round(total_score) >= 1) } 

從這個輸入是{ '聽力'=> 1, '移動'=> 2},我需要產生這個:

Score.joins(:target_disability).where{ (target_disabilities.name == 'hearing') & (round(total_score) >= 1) | (target_disabilities.name == 'mobility') & (round(total_score) >= 2) } 

等等......

這又如何推廣?因爲我有時輸入有3個或4個按鍵......有時1 ...

回答

2

假設你的散列是my_params

@scores = Score.joins(:target_disability).where do 
    my_params.map{|k,v| (target_disabilities.name==k) & (round(total_score)>=v) }.inject(:|) 
end 
+0

你可以看看這個給我嗎? http://stackoverflow.com/questions/14654010/squeel-and-rails-dynamic-where-clause –