开发者

Concatenate (glue) where conditions by OR or AND (Arel, Rails3)

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


are you looking for the form:

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

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


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)))


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'" 
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜