OBLSK Logo

Finder methods in Rails Active Record

Active Record in Ruby on Rails is used for representing business data and logic in your application. Active Record makes it easier to interact with data stored in a persistence layer such as a database by providing options for taking action on the data without needed to write explicit SQL queries or utilize other database interaction mechanisms.

One of the tools in Active Record you will use often is finder methods. In this post, we’ll visit some common finder methods that Active Record make available and call out some other cool methods that are nice to have in your toolkit.

Let’s start with the most common ones:

find

    User.find(23) # Find the user with id 23
User.find(23, 25) # Find the users with id 23, and 25 returned in an array
    

If there is no user for the id passed in, the ActiveRecord::RecordNotFound exception is raised.

find_by

        User.find_by(name: 'Michael Jordan') # Find the user named Michael Jordan
User.find_by(address: 'Bulls Way, Chicago') # Find the user with the Bulls Way address
    

Unlike find, find_by will not throw an exception if the record is not found, unless you add the !

        User.find_by!(name: 'Michael Jordan') # Find the user or raise exception
User.find_by!(address: 'Bulls Way, Chicago') # Find the user or raise exceptions
    

where to search on multiple attributes

        User.where(name: 'Michael Jordan', address: 'Bulls Way, Chicago') 
    

exists?

        User.exists?(23) # Return true if a user with id 23 exists or false
    

first, last, fifth, third_to_last, etc.

User.first # Find the first user
User.last # Find the last user
User.fifth # Find the fifth user
User.third_to_last # Find the user that is third before last

I hope you enjoyed exploring finder methods in Active Record. If you want more details, check out the Active Record finder methods Rails API documentation.