Andy Harvey
Andy Harvey

Reputation: 12653

How to count "days with records" in Rails?

Rails adds and populates a created_at column for new records.

How can I use the to count the number of days that have records within a specified timeframe? (note: counting days, not counting records).

For example, say I have a Post model, how can I calculate how many days in the last year have a Post?

Upvotes: 2

Views: 310

Answers (1)

Nick Colgan
Nick Colgan

Reputation: 5508

Since you asked for the ruby way, here it is:

Post.where('created_at >= ?', 1.year.ago).map { |p| p.created_at.beginning_of_day }.uniq.size

Update

You can put the following in your Post model

def self.number_of_days
  where('created_at >= ?', 1.year.ago).map { |p| p.created_at.beginning_of_day }.uniq.size
end

Then in your controller you can do stuff like

@user.posts.number_of_days

Here's a more efficient way that delegates most of the work to the database (MySQL, not sure if it'll work on others):

Post.where('created_at >= ?', 1.year.ago).group('DATE(created_at)').length

Upvotes: 4

Related Questions