What are the differences between #where and #find?

The real difference is what they return when a record is found, or when it's not found. Consider the following examples:

$ User.create(name: 'Ogulcan') # creates a user with id = 1
$ User.find(1) # returns the user
$ User.where(id: 1).first # returns the user

The big difference with using #where is you can chain commands because #where actually returns an instance of ActiveRecord::Relation:

$ User.where(id: 1).first.class # returns ActiveRecord::Relation

Let's have a look at when you try to find a record that isn't existing:

$ User.find(2) # raises an exception
$ User.where(id: 2).first # nil

So here, it's obvious that when you use find to search for a record that isn't existing, you get an exception.

Read more about #where and #find in Rails API. Also, watch ActiveRecord::Relation Walkthrough video by Ryan Bates (Railscasts).

Last updated

Was this helpful?