Reputation: 926
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.
Upvotes: 9
Views: 6551
Reputation: 1310
The best way is to use the gem Groupdate
e.g User.group_by_day(:created_at).count
Allow you to order by day, week, hour
Upvotes: 3
Reputation: 15056
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 %>
Upvotes: 19
Reputation: 1177
Assumed you are using mysql and video has attribute title I am posting the following code to help you to grasp the logic ( Surely it need re-factoring )
Controller
@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] }
view
<% @videos.each do |posted_date, videos| %>
<div class="video-date"><%= Date.parse(posted_date.to_s).strftime("%b %d, %Y") %> </div>
<%= videos.join(", ") %>
<% end %>
Upvotes: 0
Reputation: 7078
First of all it makes no sense to call only videos from today and then run through all videos.
I would try it this way:
@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 %>
It should give you a Video list with "Date: Video Title" for the actual month.
Upvotes: 1