Active Record Queries Cheat Sheet
Carisa Elam
Posted on August 16, 2024
Active Record allows you to execute SQL commands using Ruby. This guide cuts through the fluff to provide a simple reference for some common Active Record queries. For each query, you’ll find the SQL equivalent and a brief description of what it returns, making it easy to see how the methods map to SQL commands.
find
-
SQL Equivalent:
SELECT * FROM model WHERE (model.id = :id)
- Returns: the record with the specific ID.
take
-
SQL Equivalent:
SELECT * FROM model LIMIT 1
- Returns: the record without any ordering
first
-
SQL Equivalent:
SELECT * FROM model ORDER BY model.id ASC LIMIT 1
- Returns: the record with the first primary key that exists
last
-
SQL Equivalent:
SELECT * FROM model ORDER BY model.id DESC LIMIT 1
- Returns: the record with the last primary key that exists
find_by
-
SQL Equivalent:
SELECT * FROM model WHERE (model.parameter = 'foo') LIMIT 1
- Returns: the first record matching the condition
This is not meant to be an exhaustive guide.
For more information, see the Rails Guides: Active Record Query Interface.
👋Connect with me on Github or LinkedIn.
I'd love to hear your thoughts!
💖 💪 🙅 🚩
Carisa Elam
Posted on August 16, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.