From b27879210fac9746903a114fe87b5716a3fdf2f7 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Thu, 11 Jun 2020 13:35:48 -0500 Subject: [PATCH] Add Query A Single Value From The Database as a rails til --- README.md | 3 ++- .../query-a-single-value-from-the-database.md | 22 +++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) create mode 100644 rails/query-a-single-value-from-the-database.md diff --git a/README.md b/README.md index 66e59b6..7bf5d8b 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ and pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud). -_924 TILs and counting..._ +_925 TILs and counting..._ --- @@ -582,6 +582,7 @@ _924 TILs and counting..._ - [Perform SQL Explain With ActiveRecord](rails/perform-sql-explain-with-activerecord.md) - [Polymorphic Path Helpers](rails/polymorphic-path-helpers.md) - [Pretend Generations](rails/pretend-generations.md) +- [Query A Single Value From The Database](rails/query-a-single-value-from-the-database.md) - [Read-Only Models](rails/read-only-models.md) - [Remove The Default Value On A Column](rails/remove-the-default-value-on-a-column.md) - [Rescue From](rails/rescue-from.md) diff --git a/rails/query-a-single-value-from-the-database.md b/rails/query-a-single-value-from-the-database.md new file mode 100644 index 0000000..752a4aa --- /dev/null +++ b/rails/query-a-single-value-from-the-database.md @@ -0,0 +1,22 @@ +# Query A Single Value From The Database + +In a Rails context, most database interactions tend to happen through the ORM +(e.g. `Book.find("123")`). There is a general purpose escape hatch that lets +you execute a SQL statement directly against the DB -- `execute`. The resulting +value of `execute`, however, tends to be a little clunky to work with. + +If you just need a single value from the DB, use the +[`select_value`](https://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/DatabaseStatements.html#method-i-select_value) +method. + +```ruby +> statement = "select gen_random_uuid()" +> ActiveRecord::Base.connection.select_value(statement) + (5.0ms) select gen_random_uuid() + => "abc2e780-f442-418b-afa3-56f0ccd0a903" +``` + +This is the cleanest way to get the result of a "single value" query. + +If you happen to pass in a query that results in more than one row or column, +it will return the value of the first column from the first row.