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

 ̄綄美尐妖づ 提交于 2019-12-21 04:57:24

问题


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


来源:https://stackoverflow.com/questions/4112186/concatenate-glue-where-conditions-by-or-or-and-arel-rails3

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