Ruby on Rails: How to get the current week and loop through it to display its days?
calendar, date, ruby-on-rails, time
Solution
Try this in your controller where you're setting the `@days_from_this_week`
today = Date.today # Today's date
@days_from_this_week = (today.at_beginning_of_week..today.at_end_of_week).map
To show what this does:
> (today.at_beginning_of_week..today.at_end_of_week).map.each { |day| day }
> [Mon, 12 Aug 2013, Tue, 13 Aug 2013, Wed, 14 Aug 2013, Thu, 15 Aug 2013, Fri, 16 Aug 2013, Sat, 17 Aug 2013, Sun, 18 Aug 2013]
Update to additional request of querying articles by published on:
Find all the articles between start date's midnight to next day.
start_time = Time.parse(date.to_s)
end_time = 1.day.since(start_time)
Article.where('published_on >= ? and published_on < ?', start_time, end_time)
Problem
The above picture is what I mean. I think the code should be something like: ``` <% @days_from_this_week.each do |day| %> <%= day.name %> <!--e.g. Monday--> <% day.sessions do |session| %> <% @session_categories.each do |category| %> <!--categories means the Sesion1/2/3/4 category A day's sessionX could be empty, so we have to determine wheather a session matches its cateogry, and then display it in the table --> <% if session.category == category %> <%= session.content %> <% end %> <% end %> <% end %> <% end %> ``` But how to get the `current week`? And how to get the `name of a day`? And to navigate through this calendar, `pre_week` and `next_week` is also needed. I found`prev_week` and `next_week` method, but it seems like return a certain day after a week, which is not I need. A possible solution is here, but I don't know how to use it. UPDATE: I found a workable solution, but still looking for better code: ``` <!-- @date = params[:date] ? Date.parse(params[:date]) : Date.today first=@date.at_beginning_of_week last=@date.at_beginning_of_week + 6 @days= (first..last).to_a--> <% @days.each do |day| %> <div> <%= day %> </div> <% end %> ```