I’ve got a Relationships class and i’d like to spit out a list of how many friends a user had on a specific date range (between today and 4 weeks ago).
I’ve tried the following in an html.erb but it doesn’t appear to be working:
<table>
<% rightnow = DateTime.now.to_i %>
<% twentyeight = Time.at(rightnow).to_time - 28.days %>
<% twght = twentyeight.to_i %>
<% (twght..rightnow).step(1.day).map do |time| %>
<tr><th><%= Time.at(time).strftime("%a %b %y") %></th></tr>
<tr><td><%= Relationship.where(:follower_id => @user.id, :created_at => from .. to time ).count %></td></tr>
</table>
I suspect the answer might be along the lines of this one but i don’t know how to implement it… Ruby count items by date
Also, as i’m still grappling with MVC, how might i clean up the code? I tried creating a method in my users_controller but was unable to succesfully call it.
Cheers.
Edit:
Here is another attempt at it, which works. Feedback welcome:
<tfoot>
<% before = DateTime.now - 28.days%>
<% following = Relationship.where(:followed_id => @user.id) %>
<tr>
<% before.step(before + 28, 1) do |time| %>
<th><%= time.strftime("%a %b #{time.day.ordinalize}") %></th>
<% end %>
<% before.step(before + 28, 1) do |time| %>
<td>
<%= following.all(:conditions => ["created_at < ?", time.end_of_day]).count %>
</td><% end %>
</tr>
</tbody>
</table>
I’m going to skip the part where we pop the ‘why?’ stack. So let’s say you’re looking at the index view of the Relationships controller, for the sake of argument. Most of that code belongs in the controller, so let’s start with the easy case:
in your view:
This will show how many relationships you created in the last 28 days. This doesn’t get you to your running tally though, so let’s refactor the design a bit by adding a method to your model:
then your view will become: