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

3 回答 3

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 %>
于 2013-10-23T09:18:32.627 回答
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 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 %>
于 2013-10-23T09:15:11.430 回答
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 %>

注意:我没有测试过代码

于 2013-10-23T10:07:20.607 回答