ActiveRecord: Top 10 Ways To Query Single Record
Explaining 10 must known query methods to fetch single records
Published in
7 min readFeb 6, 2024
Introduction
In this article, we are covering top 10 query methods to fetch single record from the database table. This article includes fetching single records with addition ordering and filter criterias along with examples.
Model
- For example purpose we will take Product as our sample model:
irb(main):018:0> Product
=> Product(id: integer, name: string, description: text, created_at: datetime, updated_at: datetime)
irb(main):032:0> Product.all.to_a
Product Load (0.8ms) SELECT "products".* FROM "products"
=>
[#<Product:0x00000001142926c8 id: 1, name: "iphone1", description: "desc", created_at: Sat, 20 May 2023 00:49:44.987968000 UTC +00:00, updated_at: Sun, 04 Feb 2024 15:20:47.842524000 UTC +00:00>,
#<Product:0x0000000114292588 id: 2, name: "iphone2", description: "desc", created_at: Sat, 20 May 2023 00:49:51.637848000 UTC +00:00, updated_at: Sun, 04 Feb 2024 15:21:04.847528000 UTC +00:00>,
#<Product:0x0000000114292448 id: 3, name: "iphone3", description: "desc", created_at: Sat, 20 May 2023 00:49:53.202945000 UTC +00:00, updated_at: Sun, 04 Feb 2024 15:21:12.453226000 UTC +00:00>…