diff --git a/README.md b/README.md index 025ce41..697b5f5 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). -_886 TILs and counting..._ +_887 TILs and counting..._ --- @@ -531,6 +531,7 @@ _886 TILs and counting..._ - [Disambiguate Where In A Joined Relation](rails/disambiguate-where-in-a-joined-relation.md) - [Ensure Migrations Use The Latest Schema](rails/ensure-migrations-use-the-latest-schema.md) - [Generating And Executing SQL](rails/generating-and-executing-sql.md) +- [Get An Array Of Values From The Database](rails/get-an-array-of-values-from-the-database.md) - [Get The Column Names For A Model](rails/get-the-column-names-for-a-model.md) - [Hash Slicing](rails/hash-slicing.md) - [Ignore Poltergeist JavaScript Errors](rails/ignore-poltergeist-javascript-errors.md) diff --git a/rails/get-an-array-of-values-from-the-database.md b/rails/get-an-array-of-values-from-the-database.md new file mode 100644 index 0000000..9f952ee --- /dev/null +++ b/rails/get-an-array-of-values-from-the-database.md @@ -0,0 +1,40 @@ +# Get An Array Of Values From The Database + +We generally get data from our database through [ActiveRecord +models](https://api.rubyonrails.org/classes/ActiveRecord/Base.html): + +```ruby +> Product.where(available: true).pluck(:sku) +[ "efg-1234", "pqr-3455", ... ] +``` + +If we need to do a more specialized query, we might reach for +[`execute`](https://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/DatabaseStatements.html#method-i-execute): + +```ruby +> ActiveRecord::Base.connection.execute(<<-SQL) + select split_part(sku, '-', 1) product_type + from products + where available = true; + SQL +[{ "product_type" => "efg" }, { "product_type" => "pqr" }, ... ] +``` + +The results are bundled up in a predictable, but verbose array of hashes. + +We could trim the result down to just the values using either +[`select_values`](https://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/DatabaseStatements.html#method-i-select_values) +or +[`select_rows`](https://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/DatabaseStatements.html#method-i-select_rows): + +```ruby +> ActiveRecord::Base.connection.select_values(<<-SQL) + select split_part(sku, '-', 1) product_type + from products + where available = true; + SQL +[ "efg", "pqr", ... ] +``` + +If the SQL statement is to return more than one row in the result, then you'll +want `select_rows` instead of `select_values`.