如何检索在特定日期创建的所有记录?

时间:2013-10-23 09:10:51

标签: ruby-on-rails ruby ruby-on-rails-3

我在时间戳(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 %>

3 个答案:

答案 0 :(得分: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 %>

答案 1 :(得分: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 %>

答案 2 :(得分: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 %>

注意:我没有测试过代码