7

我正在尝试循环发布由 created_at 每天分组的视频。

例如:

2012 年 12 月 5 日 - 视频 9 视频 8 视频 7

2012 年 12 月 4 日 - 视频 6 视频 5

2012 年 12 月 3 日 - 视频 4 视频 3 视频 2 视频 1

视频控制器:

  def index
    @title = 'Hip Hop Videos, Breaking News, Videos, And Funny Shxt | HOTDROPHIPHOP'
    @description = ''
    @videos = Video.all
    @days = Video.where(:created_at == Time.today )
  end

查看文件:

<% @days.each do |day| %>

  <div class="video-date">December 4, 2012</div>

  <% @videos.each do |video| %>
  <% end %>

<% end %>

我还需要让那个 div 也显示当天的日期。

我四处搜寻,找不到解决方案,并尝试了 group_by (这似乎是最干净的),但无法使其正常工作。我的 Rails 有点生疏,因为我已经好几个月没碰它了。

4

4 回答 4

17

你可以这样做:

@videos = Video.where(Video.arel_table[:created_at].gteq(some_date_value))
@video_days = @videos.group_by {|video| video.created_at.to_date }

where@video_days将是{some_date_value: [{video1}, {video2}, etc], next_date_value: [{video3}, {video4}, etc], etc...}.

由于您.to_datecreated_at现场呼叫,它将删除所有时间信息,有效地将所有内容按天分组。

您可以像这样循环遍历它:

<% @video_days.each do |day, videos| %>
  <%= day.strftime("some format") %>
  <% videos.each do |video| %>
    <%= #output videos how you see fit %>
  <% end %>
<% end %>
于 2012-12-06T17:24:28.317 回答
3

最好的方法是使用 gem Groupdate

例如 User.group_by_day(:created_at).count

允许您按天、周、小时订购

于 2016-07-25T21:48:57.857 回答
1

首先,从今天开始只调用视频然后运行所有视频是没有意义的。

我会这样尝试:

控制器

@videos = Video.all(:conditions => ["created_at >= ?", Date.today.at_beginning_of_month])

看法

<% Date.today.at_beginning_of_month.upto(Date.today).each do |date| %>
  <%= date %>: <%= @videos.select{|u| u.created_at == date }.title %>
<% end %>

它应该为您提供一个视频列表,其中包含实际月份的“日期:视频标题”。

于 2012-12-06T17:07:49.967 回答
0

假设您使用的是 mysql 并且 video 具有属性 title 我发布以下代码以帮助您掌握逻辑(当然它需要重新分解)

控制器

@videos = {}
videos =  Video.order("DATE(created_at) DESC, title ASC").select("DATE(created_at) as created_at, title, id" )

videos.collect{|x| @videos[x.created_at.to_s] = @videos[x.created_at.to_s] ? @videos[x.created_at.to_s] << x.title : [x.title]  }

看法

<% @videos.each do |posted_date, videos| %>
  <div class="video-date"><%= Date.parse(posted_date.to_s).strftime("%b %d, %Y") %> </div> 
  <%= videos.join(", ") %>
 <% end %>
于 2012-12-06T17:20:52.443 回答