mirror of
https://github.com/jbranchaud/til
synced 2026-01-03 07:08:01 +00:00
Add Select Values For SQL Counts as a rails til.
This commit is contained in:
14
rails/select-value-for-sql-counts.md
Normal file
14
rails/select-value-for-sql-counts.md
Normal 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
|
||||
```
|
||||
Reference in New Issue
Block a user