如何在ActiveRecord查询中使用OR条件
我想抓住所有提供电子邮件的用户或者名字和姓氏。 例如:
users = User.where(:first_name => "James", :last_name => "Scott")
这将返回所有具有名字“James”和“Scott”的用户。
users = User.where(:email => "james@gmail.com")
这将返回用户的电子邮件为“james@gmail.com”。
有没有办法做一个where
子句来返回具有相同名字和姓氏的用户以及用户匹配的查询或者我需要在2个单独的where
子句中进行合并的用户。
Rails 5带有一个or
一个方法 。
此方法接受ActiveRecord::Relation
对象。 例如:
User.where(first_name: 'James', last_name: 'Scott') .or(User.where(email: 'james@gmail.com'))
试试这个:
users = User.where("(first_name = 'James' and last_name = 'Scott') or email = 'james@gmail.com'")
要插入变量:
users = User.where("(first_name = ? and last_name = ?) or email = ?", first_name, last_name, email)
如果您更喜欢DSL方法(没有SQL),可以使用底层的Arel层:
t = User.arel_table users = User.where( (t[:first_name].eq('Ernie').and(t[:last_name].eq('Scott')). or(t[:email].eq('james#gmail.com')) )
这有点难看,但是如果你在Arel上使用一些包装器(例如, 这个 ),那么代码就更好了:
users = User.where( ((User[:first_name] == 'Ernie') & (User[:last_name] == 'Scott')) | (User[:email] == 'james#gmail.com') )
如果您不想像其他人提到的那样编写SQL,您可以直接访问arel结构(看起来像另一个答案)或使用squeel gem更优雅地执行它:
User.where{(first_name == 'Ernie') & (last_name == 'Scott') | (email == 'james#gmail.com')}
您可以使用字符串条件,如Client.where("orders_count = ? AND locked = ?", params[:orders], false)
,并将OR
与AND
结合使用。 但请注意这些运营商的优先级。
Cf Active Record Query Interface指南