From 9e25c980a06b3447622b83608fe866b9d1d9d390 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Mon, 11 Oct 2021 18:31:27 -0500 Subject: [PATCH] Add Grab A Random Record From The Database as a Rails til --- README.md | 3 +- .../grab-a-random-record-from-the-database.md | 31 +++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 rails/grab-a-random-record-from-the-database.md diff --git a/README.md b/README.md index 45b824b..e99f4f9 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1157 TILs and counting..._ +_1158 TILs and counting..._ --- @@ -705,6 +705,7 @@ _1157 TILs and counting..._ - [Get An Empty ActiveRecord Relation](rails/get-an-empty-activerecord-relation.md) - [Get The Column Names For A Model](rails/get-the-column-names-for-a-model.md) - [Get The Current Time](rails/get-the-current-time.md) +- [Grab A Random Record From The Database](rails/grab-a-random-record-from-the-database.md) - [Handle Named Arguments In A Rake Task](rails/handle-named-arguments-in-a-rake-task.md) - [Hash Slicing](rails/hash-slicing.md) - [Ignore Poltergeist JavaScript Errors](rails/ignore-poltergeist-javascript-errors.md) diff --git a/rails/grab-a-random-record-from-the-database.md b/rails/grab-a-random-record-from-the-database.md new file mode 100644 index 0000000..629fdc5 --- /dev/null +++ b/rails/grab-a-random-record-from-the-database.md @@ -0,0 +1,31 @@ +# Grab A Random Record From The Database + +I recently learned of a clever way to grab a random record for a particular +model from the database. This is handy if you are poking around in the database +to see what some records look like. + +Order the records for that table randomly and then grab the first. + +```ruby +Event.order('random()').first +``` + +This grabs a random `Event` record from the `events` table. + +Note, however, that for Rails 6+, this approach won't work. Because of some +extra safety measures around executing raw SQL, you'll instead have to write +the above as: + +```ruby +Event.order( Arel.sql('random()') ).first +``` + +This uses +[`Arel.sql`](https://api.rubyonrails.org/classes/Arel.html#method-c-sql) to +mark `'random()'` as a known-safe string of SQL. + +Because we are explicitly passing a string that represents a known-safe +function call, this is fine. Take care to not pass any user-generated SQL in a +scenario like this unless you know what you're doing. + +[source](https://stackoverflow.com/a/49525874/535590)