Web Development

Do you want to get the last few records on a database table using the Rails ActiveRecord? Here’s a simple way to do it:

Get the last record

Grower.last
#<Grower:0x007fdf8e55de10
 id: 713,
 name: "Diamondback",
 created_at: Tue, 06 Mar 2018 03:16:09 EST -05:00,
 updated_at: Tue, 06 Mar 2018 03:16:09 EST -05:00>

Get the last few records

Grower.last(5)
[#<Grower:0x007fdf917e7ed0
 id: 709,
 name: "Crossbones",
 created_at: Tue, 06 Mar 2018 03:16:09 EST -05:00,
 updated_at: Tue, 06 Mar 2018 03:16:09 EST -05:00>,
#<Grower:0x007fdf99a50070
 id: 710,
 name: "Winter Soldier",
 created_at: Tue, 06 Mar 2018 03:16:19 EST -05:00,
 updated_at: Tue, 06 Mar 2018 03:16:19 EST -05:00>,
#<Grower:0x007fdf99a501b0
 id: 711,
 name: "Punisher",
 created_at: Tue, 06 Mar 2018 03:16:29 EST -05:00,
 updated_at: Tue, 06 Mar 2018 03:16:29 EST -05:00>,
#<Grower:0x007fdf99a502f0
 id: 712,
 name: "TaskMaster",
 created_at: Tue, 06 Mar 2018 03:16:30 EST -05:00,
 updated_at: Tue, 06 Mar 2018 03:16:30 EST -05:00>,
#<Grower:0x007fdf99a52de8
 id: 713,
 name: "Diamondback",
 created_at: Tue, 06 Mar 2018 03:16:39 EST -05:00,
 updated_at: Tue, 06 Mar 2018 03:16:39 EST -05:00>]

Easy Peezy!