DEV Community

Cover image for Active Record Queries Cheat Sheet
Carisa Elam
Carisa Elam

Posted on

Active Record Queries Cheat Sheet

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!

Top comments (0)