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

Ruby on rails 如何检索在特定日期创建的所有记录?,ruby-on-rails,ruby,ruby-on-rails-3,Ruby On Rails,Ruby,Ruby On Rails 3,我对时间戳(在创建时)和今天的感到困惑 我想展示包括今天在内的过去7天的报告。 报告显示了每天发表的所有评论的数量 如何修复下面的代码?到底发生了什么 <% user_ids = User.all %> <% commentable = User.base_class.name.to_s %> <% check_date = Date.today - 7 %> <% 7.times do %> <% @comments_coun

我对时间戳(在创建时)和今天的
感到困惑

我想展示包括今天在内的过去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 %>

无,创建时间=>user\u id=>user\u id,:commentable\u type=>commentable)。计数%>
发表评论!在
类似于:

range = "created_at #{(5.days.ago.utc...Time.now.utc).to_s(:db)}"
Category.where(:conditions => range)
这是一个很好的参考:


关于你的问题:

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

nil,:created_at=>date_range,:user_id=>user_id,:commentable_type=>commentable)。计数%>
发表评论!在

您应该这样做

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

nil,:user_id=>user_id,:commentable_type=>commentable)。选择{{comment | comment.created_at.to_date==date}。计数%>
发表评论!在

首先:不要在视图中进行查询,使用控制器获取数据并将其传递给视图。如果要使用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 %>


注意:我还没有测试代码

你能自定义我的原始代码让我更深入地理解吗?我想用我的代码。谢谢,但你一定要两个都试一下&看看哪一个效果最好@Amit Thawait的代码在编程上比我的更干净谢谢!!您能否将日期直接放在
where()
的内部?因为,
date
是datetime,而
created\u at
是timetime,所以您不能使用我的
check\u date
?不要使用
日期
检查日期是不需要的,因为我们正在循环使用日期本身,请尝试我的更新答案,如果它不起作用,请告诉我。。