[Rails] Different find methods

Tags
Rails
Engineering
Created
Oct 8, 2023 11:10 PM
Edited
Oct 8, 2023
Description
find vs find_by vs find_by_field

Summary

In my opinion, where is the best and can be chained with other methods. where is also straightforward if you know SQL.

find

  • Usually use id to search
  • Can also return an array
# find by id
Person.find(1)       # returns the object for ID = 1
Person.find(1, 2, 6) # returns an array for objects with IDs in (1, 2, 6)
Person.find([7, 17]) # returns an array for objects with IDs in (7, 17)
Person.find([1])     # returns an array for the object with ID = 1
Person.find(1, :conditions => "administrator = 1", :order => "created_on DESC")
  • Raises ActiveRecord::RecordNotFound if not found

find_by

  • Only returns the first found record
    • So make sure the field to look up is unique
  • find_by only returns nil if not found
    • You can use find_by!
Post.find_by name: 'Spartacus', rating: 4
Post.find_by "published_at < ?", 2.weeks.ago

find_by_field

  • Dynamic finder; crazy Rails magic…
  • find_by_field(value) is pretty much find_by(field: value)

Source