1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 23:28:02 +00:00

Add Select Values For SQL Counts as a rails til.

This commit is contained in:
jbranchaud
2015-07-13 22:16:37 -05:00
parent b423057105
commit d8f9a68684
2 changed files with 15 additions and 0 deletions

View File

@@ -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

View File

@@ -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
```