How to use OR condition in ActiveRecord query

后端 未结 5 1097
轻奢々
轻奢々 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:45

    You could use string conditions, as in Client.where("orders_count = ? AND locked = ?", params[:orders], false), and use OR in conjunction with AND. Be careful with the priority of those operators though.

    Cf Active Record Query Interface guide

    0 讨论(0)
  • 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')
    )
    
    0 讨论(0)
  • 2020-12-09 02:54

    If you don't want to write SQL as the others have mentioned, you could access the arel structures directly (looks like another answer has that) or use the squeel gem to do it much more elegantly:

    User.where{(first_name == 'Ernie') & (last_name == 'Scott') | (email == 'james#gmail.com')}
    
    0 讨论(0)
  • 2020-12-09 02:55

    Try this:

    users = User.where("(first_name = 'James' and last_name = 'Scott') or email = 'james@gmail.com'")
    

    To interpolate variables:

    users = User.where("(first_name = ? and last_name = ?) or email = ?", first_name, last_name, email)
    
    0 讨论(0)
  • 2020-12-09 03:12

    Rails 5 comes with an or method.

    This method accepts an ActiveRecord::Relation object. eg:

    User.where(first_name: 'James', last_name: 'Scott')
        .or(User.where(email: 'james@gmail.com'))
    
    0 讨论(0)
提交回复
热议问题