How to use OR condition in ActiveRecord query

后端 未结 5 1116
轻奢々
轻奢々 2020-12-09 02:38

I want to grab all the users that either have an email as the one supplied or the first and last name. So for example:

users = User.where(:first_name => \         


        
5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-09 02:53

    If you prefer a DSL approach (with no SQL), can use the underlying Arel layer:

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

    That's a bit ugly, but if you use some wrapper over Arel (for example, this one), the code is much nicer:

    users = User.where(
      ((User[:first_name] == 'Ernie') & (User[:last_name] == 'Scott')) |
       (User[:email] == 'james#gmail.com')
    )
    

提交回复
热议问题