2011-06-13 36 views
0

我有一个关系类,我想吐出一个用户在特定日期范围(今天到4周前)有多少朋友的列表。在Ruby中如何计算特定的created_at日期?

我已经试过在html.erb以下,但它似乎没有奏效:

<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> 

我怀疑,答案可能是沿着这一条线,但我不知道如何实现它... Ruby count items by date

此外,因为我仍然与MVC拼杀,我该如何清理代码?我试图在我的users_controller中创建一个方法,但无法成功调用它。

干杯。

编辑:

这是另一个尝试它,它的工作原理。反馈欢迎:

<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(前+ 28,1)做|时间| %>

<td> 
<%= following.all(:conditions => ["created_at < ?", time.end_of_day]).count %> 
</td><% end %> 
</tr> 
</tbody> 
</table> 

回答

1

我要跳过我们弹出的部分'为什么?'叠加。假设您正在查看关系控制器的索引视图,以便进行论证。该代码的绝大部分属于控制器,所以让我们先从简单的情况:

class RelationshipsController < ApplicationController 
    before_filter :set_user #whatever you do to load your currently logged in user 
    def index 
    @relationships = @user.relationships.where(:created_at => 28.days.ago..Date.today) 
    end 
end 

在您的视图:

<table> 
    <tr><th><%= Time.at(time).strftime("%a %b %y") %></th></tr> 
    <tr><td><%= @relationships.count %></td></tr> 
</table> 

这将显示您在过去28天内有多少关系产生的。这不会让你到你的流水账了,所以让我们重构设计有点通过添加一个方法到模型:

class Relationship < ActiveRecord::Base 
    #... skip other stuff 
    def self.relationship_count_for_days(start_date, end_date) 
    where(:created_at => start_date..end_date).count 
    end 
end 

那么你的观点将成为:

<table> 
    <% 28.downto(1) do |days_ago| %> 
    <tr><th><%= days_ago.days.ago.to_time.strftime("%a %b %y") %></th></tr> 
    <tr><td><%= @relationships.relationship_count_for_days(28.days.ago, days_ago.days.ago) %></td></tr> 
    <% end 
</table> 
+0

干杯@karmajunkie和鲍里斯。我现在就试试。与此同时,我想出了另一种(非MVC友好型)解决方案。我已经编辑了我的问题,如果你能给我一些反馈意见。 – Ribena 2011-06-14 06:33:21

+0

谢谢。我已经实现了一个你的代码版本,它的工作很好。但我想我得到更多的查询比我在我的编辑张贴的代码。有没有办法减少你的代码查询的数量? – Ribena 2011-06-14 15:10:24

+0

我不得不看你实际上在做什么,但我的建议是不要太担心查询。当它成为瓶颈时,解决问题。对于新的围栏开发者来说,这通常是一件困难的事情,没有理由变得sl,不驯,而是优化重要的事情。例如,这是一个易于缓存的视图,可能会首次运行一些额外的查询,但之后每次都会运行0,直到缓存过期或无效。 – karmajunkie 2011-06-15 21:17:07

1

也许你应该尝试做下一个:
在你的控制器:

@relationships = Relationship.where("created_at BETWEEN ? AND ?", your_start_date, your_end_date) 

,然后在视图中,可以通过@relationships迭代和builld演示

* your_start_date - 可以是Time.now - 28.days