I have 2 tables: Client
and Document
A client
has many documents
Client |
---|
id |
name |
Document |
---|
id |
name |
expiration_date |
client_id |
expiration_date format is YYYY-MM-DD
And I want to return a table like this:
id | name | documents_count | expired | 30 days |
---|---|---|---|---|
1 | client a | 10 | 5 | 2 |
2 | client b | 8 | 8 | 0 |
3 | client c | 13 | 0 | 10 |
Right now my code is like this:
Client.all.left_joins(:documents).group(:id).select('clients.*, COUNT(documents.id) AS documents_count')
And I am missing the last 2 columns.
How can I get those 2 columns?
I tried:
Client.all.left_joins(:documents).group(:id).select("clients.*, COUNT(documents.id) AS documents_count, COUNT(documents.expiration < #{Date.today}) AS expired")
but the expired columns return booleans and not a number.
id | name | documents_count | expired |
---|---|---|---|
1 | client a | 10 | true |
2 | client b | 8 | true |
3 | client c | 13 | true |