按天创建分组_At

Jam*_*s F 6 ruby-on-rails ruby-on-rails-3

我想通过created_at发布每天分组的视频.

例如:

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

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

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

videos_controller:

  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
Run Code Online (Sandbox Code Playgroud)

查看文件:

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

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

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

<% end %>
Run Code Online (Sandbox Code Playgroud)

我还需要得到那个div来显示那天的日期.

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

Sea*_*ill 13

你可以这样做:

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

哪个@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 %>
Run Code Online (Sandbox Code Playgroud)