From d8f9a6868487b7e863379c988326b418e6fe1002 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Mon, 13 Jul 2015 22:16:37 -0500 Subject: [PATCH] Add Select Values For SQL Counts as a rails til. --- README.md | 1 + rails/select-value-for-sql-counts.md | 14 ++++++++++++++ 2 files changed, 15 insertions(+) create mode 100644 rails/select-value-for-sql-counts.md diff --git a/README.md b/README.md index 322a83f..b839685 100644 --- a/README.md +++ b/README.md @@ -89,6 +89,7 @@ smart people at [Hashrocket](http://hashrocket.com/). - [Creating Records of Has_One Associations](rails/creating-records-of-has-one-associations.md) - [Pretend Generations](rails/pretend-generations.md) - [Retrieve An Object If It Exists](rails/retrieve-an-object-if-it-exists.md) +- [Select Value For SQL Counts](rails/select-values-for-sql-counts.md) - [Show Pending Migrations](rails/show-pending-migrations.md) ### ruby diff --git a/rails/select-value-for-sql-counts.md b/rails/select-value-for-sql-counts.md new file mode 100644 index 0000000..22eb325 --- /dev/null +++ b/rails/select-value-for-sql-counts.md @@ -0,0 +1,14 @@ +# Select Value For SQL Counts + +If you are like me and prefer writing raw SQL over the Arel DSL for counting +stuff in your database, then the `select_value` method will come in handy. +Write a command similar to the following with a type cast to get the count +of _whatever_. + +```ruby +> sql = 'select count(*) from posts where published_at is not null' +=> "select count(*) from posts where published_at is not null" +> ActiveRecord::Base.connection.select_value(sql).to_i + (0.6ms) select count(*) from posts where published_at is not null +=> 42 +```