Concatenate (glue) where conditions by OR or AND (

2020-06-18 10:10发布

问题:

I have several complex queries (using subqueries, etc...) and want to glue them together with OR or AND statement.

For example:

where1=table.where(...)
where2=table.where(...)

I would like something like

where3=where1.or where2

Next example doesn't work for me:

users.where(users[:name].eq('bob').or(users[:age].lt(25)))

because of I have several where(..) queries and I want to concatenate them.

In other words

I have 3 methods: first return first where, second-second, third - OR concatenation.

I must have able to use all 3 methods in my application and save DRY code

回答1:

are you looking for the form:

users.where(users[:name].eq('bob').or(users[:age].lt(25)))

docs: https://github.com/rails/arel



回答2:

users.where(users[:name].eq('bob').or(users[:age].lt(25))) is close, but you need to get the arel_table to specify the columns, e.g.

t = User.arel_table
User.where(t[:name].eq('bob').or(t[:age].lt(25)))


回答3:

I know that for AND concatenation you can do:

users = User.where(:name => 'jack')
users = users.where(:job => 'developer')

and you get a concatenation with AND in SQL (try it with #to_sql at the end)

Other than that you can do:

where1=table.where(...)
where2=table.where(...)
where1 & where2

example:

(User.where(:name => 'jack') & User.where(:job => 'dev')).to_sql
=> "SELECT `users`.* FROM `users` WHERE `users`.`name` = 'jack' AND `users`.`job` = 'dev'"