0

I want to count the users that registered on the website on specific periods. For example:

Today: 5

Yesterday: 7

Over last week: 28

Over last month: 101

I used this stackoveflow question that is somewhat relevant to what I want to do. But when I try to apply it it has several problems in terms of logic for what I try to do.

So what I figured out is that I should use something like:

@lastfivedays = User.where(
'created_at >= :five_days_ago',
:five_days_ago => Time.now - 5.days,
)

But where am I placing this and how do I use it in the view? Yes I am lost on how I do something like this in Rails as I am new to this. Any guidance, tip will be extremely helpful.

Community
  • 1
  • 1

2 Answers2

1

Your query should go in the controller and you can then access the instance variable in the view.

Controller:

@lastfivedays = User.where(
  'created_at >= :five_days_ago',
  :five_days_ago => 5.days.ago,
).count

View:

Number of users who registered in last 5 days: <%= @lastfivedays %>
Finbarr
  • 31,350
  • 13
  • 63
  • 94
0

I would recommend using ActiveRecord Scopes

You could have something like:

class User < ActiveRecord::Base
...

  scope :joined_within_five_days, -> { where('created_at >= :five_days_ago',
:five_days_ago => Time.now - 5.days,) }

...
end

Your controller could then use the approriate one. For example

@users = User.joined_within_five_days
Srikanth Venugopalan
  • 9,011
  • 3
  • 36
  • 76