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>
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)")
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