I am trying to get a loop to post videos grouped by each day by created_at.
For example:
December 5, 2012 - Video 9 Video 8 Video 7
December 4, 2012 - Video 6 Video 5
December 3, 2012 - Video 4 Video 3 Video 2 Video 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
View file:
<% @days.each do |day| %>
<div class="video-date">December 4, 2012</div>
<% @videos.each do |video| %>
<% end %>
<% end %>
I also need to get that div to show that day's date as well.
I searched around and couldn't find a solution and tried the group_by (which seemed the cleanest) but couldn't get it to work. I am a bit rusty on my Rails as I haven't touched it for months.
You can do this:
@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
will be a hash in the form of {some_date_value: [{video1}, {video2}, etc], next_date_value: [{video3}, {video4}, etc], etc...}
.
Since you are calling .to_date
on the created_at
field, it will drop all of the time information, effectively grouping everything by day.
You can loop through it like:
<% @video_days.each do |day, videos| %>
<%= day.strftime("some format") %>
<% videos.each do |video| %>
<%= #output videos how you see fit %>
<% end %>
<% end %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With