Ruby on rails 如何在ActiveRecord查询中使用或条件
我想抓住所有的用户,要么有一个电子邮件作为一个提供或名字和姓氏。例如:Ruby on rails 如何在ActiveRecord查询中使用或条件,ruby-on-rails,ruby-on-rails-3,activerecord,Ruby On Rails,Ruby On Rails 3,Activerecord,我想抓住所有的用户,要么有一个电子邮件作为一个提供或名字和姓氏。例如: users = User.where(:first_name => "James", :last_name => "Scott") 它将返回所有名为“James”和“Scott”的用户 将返回用户的电子邮件为“james@gmail.com“ 是否有一种方法可以执行where子句,以返回具有相同姓名的用户和在一个where查询中匹配的电子邮件的用户,或者我是否需要对两个单独的where子句进行合并。您可以使用字
users = User.where(:first_name => "James", :last_name => "Scott")
它将返回所有名为“James”和“Scott”的用户
将返回用户的电子邮件为“james@gmail.com“
是否有一种方法可以执行
where
子句,以返回具有相同姓名的用户和在一个where
查询中匹配的电子邮件的用户,或者我是否需要对两个单独的where
子句进行合并。您可以使用字符串条件,如在Client.where中(“orders_count=?AND locked=?”,参数[:orders],false)
,并将或与和
结合使用。但要注意这些运算符的优先级
Cf试试这个:
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)
如果您不想像其他人提到的那样编写SQL,您可以直接访问arel结构(看起来另一个答案是这样的),或者使用gem更优雅地编写:
User.where{(first_name == 'Ernie') & (last_name == 'Scott') | (email == 'james#gmail.com')}
如果您喜欢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')
)
Rails 5附带了一个
此方法接受ActiveRecord::Relation
对象。例如:
User.where(first_name: 'James', last_name: 'Scott')
.or(User.where(email: 'james@gmail.com'))
有趣的包装,我一直不喜欢使用arel,但我可能不太反对它;很好。可能是@Trace的重复:你忘了选择答案或至少给出一些反馈。是的,我想那更像ruby。在任何情况下,它也需要调整以使用变量。对于Rails 5应用程序,这应该是con回避了最正确的答案。
User.where(first_name: 'James', last_name: 'Scott')
.or(User.where(email: 'james@gmail.com'))