💻
notes
  • Initial page
  • sql
    • date-and-time
    • Ordering Columns
    • Replacing Portions of Text
    • count-rows
    • Changing the Case of Strings
    • Create Excerpts with Substring
    • Transactions
    • removing-data
    • Finding Length of Strings
    • add-row-to-a-table
    • limit-and-paginate-results
    • Concatenating Strings
    • SQL JOINs
    • basic-math
    • updating-rows-in-a-table
    • Subqueries
    • Set Operations
    • SQL Basics Cheatsheet
  • ruby
    • gems
      • Auto use Ruby version with gemset
      • Must Have Gems
      • Create Devise user without any validation
    • rails
      • What are the differences between #where and #find?
  • postgresql
    • Export database dump from Heroku and import to local database
  • glossary
  • vim
    • Edit Recorded Macros
    • Sort Multiple Lines
    • Search and Replace
    • Folding
  • iTerm
  • git
    • Git
  • Command Line Utilities
  • How To Use Notes
  • Terminal Cheatsheet for Mac
Powered by GitBook
On this page

Was this helpful?

  1. ruby
  2. rails

What are the differences between #where and #find?

PreviousrailsNextpostgresql

Last updated 5 years ago

Was this helpful?

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 and in Rails API. Also, watch video by Ryan Bates (Railscasts).

#where
#find
ActiveRecord::Relation Walkthrough