2013-10-23 95 views
0

我很困惑时间戳(created_at)和today如何检索在特定日期创建的所有记录?

我想显示最近7天的报告,包括今天。
该报告显示每天发布的所有评论的数量。

如何修复下面的代码?什么来?????

<% user_ids = User.all %> 
<% commentable = User.base_class.name.to_s %> 

<% check_date = Date.today - 7 %> 

<% 7.times do %> 

    <% @comments_count = Comment.where(:deleted_at => nil, :created_at => , ??????? :user_id => user_ids, :commentable_type => commentable).count %>  

    <%= @comments_count.to_s %> comments posted! on <%= check_date.to_s %> <br /> 

    <% check_date = check_date + 1 %> 

<% end %> 

回答

2

喜欢的东西:

range = "created_at #{(5.days.ago.utc...Time.now.utc).to_s(:db)}" 
Category.where(:conditions => range) 

你一个很好的参考:Rails/SQl query help: Find all by created_at in past 7 days per each day?


对于你的问题:

<% user_ids = User.all %> 
<% commentable = User.base_class.name.to_s %> 

<% 7.times do |i| %> 

    <% check_date = Date.today - i %> 
    <% date_range = "#{(7.days.ago...check_date).to_s(:db)}" %> 

    <% @comments_count = Comment.where(:deleted_at => nil, :created_at => date_range, :user_id => user_ids, :commentable_type => commentable).count %> 

    <%= @comments_count.to_s %> comments posted! on <%= check_date.to_s %> <br /> 

    <% check_date = check_date + 1 %> 

<% end %> 
+0

你能请定制我的原始代码,让我更深入了解?我想用我的代码去。 – HUSTEN

+0

感谢您的多次尝试。我喜欢你的方式! – HUSTEN

+0

谢谢,但你一定要尝试一下,看看哪个效果最好。 @Amit Thawait的代码比我的程序更清洁 –

4

你应该做这样的事

<% user_ids = User.all %> 
<% commentable = User.base_class.name.to_s %> 

<% dates = (Date.today)..(Date.today - 6) %> 

<% dates.each do |date| %> 

    <% @comments_count = Comment.where(:deleted_at => nil, :user_id => user_ids, :commentable_type => commentable).select{|comment| comment.created_at.to_date == date}.count %>  

    <%= @comments_count.to_s %> comments posted! on <%= date.to_s %> <br /> 

<% end %> 
+0

谢谢!你可以把'date'直接放在'where()'里面吗?因为'date'是日期时间,'created_at'是时间戳 – HUSTEN

+0

也不能使用我的'check_date'吗?而不是使用'日期' – HUSTEN

+0

check_date不是必需的,因为我们正在循环使用日期本身,请尝试我更新的答案,并让我khow如果它不起作用.. –

2

首先:不要在您的视图中查询,使用控制器来获取数据并将它们传递给视图。如果您打算使用Rails进行开发并遵循原则(在这种情况下为MVC)。

你可以得到所有过去7天的评论:

@comments = Comment.group('date(created_at), user_id') :conditions => { :created_at => 7.days.ago.utc...Time.now.utc } 

然后在您的视图:

<% @comments.each do |date, count| %> 

<%= date %> 
<%= count %> 

<% end %> 

注:我没有测试过的代码

相关问题