What's the difference between `find`, `find_by`, and `where`?

Beginner

Answer

  • find: Finds by primary key, raises ActiveRecord::RecordNotFound if not found
  • find_by: Finds first record matching conditions, returns nil if not found
  • where: Returns ActiveRecord::Relation with all matching records
User.find(1)                    # Raises error if not found
User.find_by(email: "a@b.com")  # Returns nil if not found
User.where(active: true)        # Returns Relation (chainable)