Multiple Where Conditions Using Active Record
This short snippet will show you how to use multiple where clauses using Active Record
Published on:October 13, 2015
Introduction
Multiple where conditions is easy using Active Record. First, lets take a look at multiple conditions joined by and
.
Multiple Conditions using AND:
Person.where("first_name = ? AND last_name = ?", first_name, last_name)
In the example, first_name
and last_name
are variables containing the first and last name you wish to search for. Note that in this situation, we can also use LIKE
or ILIKE:
Multiple Conditions using AND along with LIKE:
Person.where("first_name LIKE '%?%' AND last_name = '%?%'", first_name, last_name)
The code above will do a wildcard search based on first/last name. This works on MySQL, PostgreSQL, and most other database engines, though you should use ILIKE for PostgreSQL. Similarly, you can do an OR clause:
Multiple Conditions using AND:
Person.where("first_name LIKE '%?%' OR last_name LIKE '%?%'", search_term, search_term)
In the example above, we used the same variable for both where conditions, though you don't need to do that.
That's it, thanks for reading!