Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails - Converting Hash of Datetimes to Dates

I am creating a calendar view based on this Railscast tutorial. In the tutorial, the :published_on field is a date field. My question is, if :published_on were a datetime field instead of a date field, how would I adjust the code below to make it work?

Migration

t.date :published_on

Controller:

def index
  @articles = Article.all
  @articles_by_date = @articles.group_by(&:published_on)
  @date = params[:date] ? Date.parse(params[:date]) : Date.today
end

View:

<div id="articles">
  <h2 id="month">
    <%= link_to "<", date: @date.prev_month %>
    <%= @date.strftime("%B %Y") %>
    <%= link_to ">", date: @date.next_month %>
  </h2>
  <%= calendar @date do |date| %>
    <%= date.day %>
    <% if @articles_by_date[date] %>
       <ul>
        <% @articles_by_date[date].each do |article| %>
          <li><%= link_to article.name, article %></li>
         <% end %>
      </ul>
    <% end %>
  <% end %>
</div>
like image 574
diasks2 Avatar asked Jan 16 '23 19:01

diasks2


1 Answers

we need to group the articles only by date not datetime:

 @articles_by_date = Article.all.group_by {|i| i.created_at.to_date}

Delete the @articles line, it doesn't look like it does anything.

That should be all.

For a rails 3.x + approach use ActiveRecord group function, it will perform the grouping using the DB, rather than instantiating all records then grouping.

@articles_by_date = Article.group("date(created_at)")
like image 107
TomDunning Avatar answered Jan 26 '23 17:01

TomDunning