开发者

How can you do a conditional where clause using AREL

开发者 https://www.devze.com 2023-03-10 09:35 出处:网络
How can you do a conditional where clause?I have a rake task that runs a query.Say I am building a query like so:

How can you do a conditional where clause? I have a rake task that runs a query. Say I am building a query like so:

residentials = Residential.where(:is_active => true)

Now if I pass a certain parameter to the rake task, I want to add to the where clause. I was thinking 开发者_StackOverflow社区something like this:

residentials.where(:something_else => true) if param_was_passed

But that just replaces the existing where clause. How can I add it to the existing where clauses?


It is possible to chain where statements

residentials = Residential.where(:is_active => true)
residentials = residentials.where(:other_thing => true) if param_was_passed

This should work.

Make sure this is not the last line in a function call; repeat the residentials variable as the last line in that case. (As per @digger69 comment)


You could build up the hash and then provide it to the .where method. Something like:

h = { }
h[:is_active] = true
h[:field_x] = true if param_was_passed

residentials = Residential.where(h)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号