I have many User objects with created_at attribute e.g.
I get objects with @users = User.all
I want get the count of User objects with various ages from creation with
@users.size
for these date ranges:
yesterday
last week
last month
last year.
How can I do it?
I use mongoid.
You can write scopes for this:
The reason we need to use a lambda here is that it delays the evaluation of the Time.now argument to when the scope is actually invoked. Without the lambda the time that would be used in the query logic would be the time that the class was first evaluated, not the scope itself.
Now we can get the counts, by simply calling:
If you want the objects:
You can use
@users_created_yesterdayin the views.Update
Well with yesterday, if you mean time between, yesterday beginning of day 0:00 and yesterday end of day 23:59, you will have to take Time zones into consideration.
Fo example, in your application.rb, if you have written:
If you have use this, all the times fetched by activerecord queries will be converted to this time zone, Central Time (US & Canada). In the database, all the times will be stored in UTC and will be converted to the time zone on fetching from the database. If you have commented out this line, default will be UTC. You can get all the time zones using the rake task
rake time:zones:allor only the US timezones usingrake time:zones:us.If you want the time zone specified in the
application.rb, you need to useTime.zone.now, in the following code. If you useTime.nowin the following code, you will get the time zone according to the time zone of your server machine.So, you can write class methods and calculate start time and end time, supply it to the scope
created_between, and you will be able to call them likeUser.created_yesterday, like we called before.Credits:
EdgeRails. Since it is Mongoid, I had to look up at Mongoid docs