问题
From this input: {'hearing' => 1} I need to generate this query
Score.joins(:target_disability).where{ (target_disabilities.name == 'hearing') & (round(total_score) >= 1) }
From this input is {'hearing' => 1, 'mobility' => 2}, I need to generate this:
Score.joins(:target_disability).where{ (target_disabilities.name == 'hearing') & (round(total_score) >= 1) | (target_disabilities.name == 'mobility') & (round(total_score) >= 2) }
And so on...
How can this be generalized? Because my input sometimes has 3 or 4 keys... sometime 1...
回答1:
Assuming your hash is in my_params
:
@scores = Score.joins(:target_disability).where do
my_params.map{|k,v| (target_disabilities.name==k) & (round(total_score)>=v) }.inject(:|)
end
来源:https://stackoverflow.com/questions/10571380/how-do-i-handle-the-where-conditions-dynamically-in-squeel