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 => \
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
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')
)
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')}
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)
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'))