Monday, January 3, 2011

[Rails] adding missing days to array of users created by day

I would like to count the number of users created each day. The
problem arises that on some days no users a created so there are gaps
in my array of users created by day. E.g.

[ ['14 Jan', 2], ['15 Jan', 4], ['17 Jan', 2] ] # [day, users created]

I've written the following code which successfully works but I'm
wondering if it can be done better as I am also wanting to sort users
by month.
So first: can it be written better
Second(if you've got time) : how would you write to get users created
in a month
------
data=[]
start_date = Date.today-1month
end_date = Date.today

results = User.find(:all,:select => 'created_at', conditions =
{:created_at => start_date..end_date}).group_by{|u|
u.created_at.to_date}.sort

#go through each date between start and end date and add 0 for missing
days
start_date.upto(end_date) do |date|
result = results.find{|r| r[0]==date}
users_count = result.nil? ? 0 : result[1].count
data << [date.strftime("%d %b"), users_count]
end
-----

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate