Ruby on Rails ActiveRecord Query Interface .where


Example

The where method is available on any ActiveRecord model and allows querying the database for a set of records matching the given criteria.

The where method accepts a hash where the keys correspond to the column names on the table that the model represents.

As a simple example, we will use the following model:

class Person < ActiveRecord::Base
  #attribute :first_name, :string
  #attribute :last_name, :string
end

To find all people with the first name of Sven:

people = Person.where(first_name: 'Sven')
people.to_sql # "SELECT * FROM people WHERE first_name='Sven'"

To find all people with the first name of Sven and last name of Schrodinger:

people = Person.where(first_name: 'Sven', last_name: 'Schrodinger')
people.to_sql # "SELECT * FROM people WHERE first_name='Sven' AND last_name='Schrodinger'"

In the above example, the sql output shows that records will only be returned if both the first_name and the last_name match.

query with OR condition

To find records with first_name == 'Bruce' OR last_name == 'Wayne'

User.where('first_name = ? or last_name = ?', 'Bruce', 'Wayne')
# SELECT "users".* FROM "users" WHERE (first_name = 'Bruce' or last_name = 'Wayne')