Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails: How to get the current week and loop through it to display its days?

enter image description here

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 foundprev_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
    [email protected]_beginning_of_week
    [email protected]_beginning_of_week + 6
    @days= (first..last).to_a-->
    <% @days.each do |day| %>
        <div>
          <%= day %>
        </div>

    <% end %>
like image 606
cqcn1991 Avatar asked Aug 13 '13 02:08

cqcn1991


1 Answers

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)
like image 131
vee Avatar answered Oct 14 '22 07:10

vee