How do I handle the where conditions dynamically in squeel?

偶尔善良 提交于 2019-12-12 18:24:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!