我用通常的CRUD动作创建了一个简单的博客应用程序。我需要按日期对评论进行分组。有类似的东西:
Grouping Blog Comments <=== Blog post title
December 19, 2013
Create controller <==== comment
Create View <==== comment
Create controller <==== comment
Create View <==== comment
December 18, 2013
draw controller <==== comment
print View <==== comment
Create controller <==== comment
Create View <==== comment
请注意,我将控制器标题命名为评论。
headlines_controller.rb
class HeadlinesController < ApplicationController
def create
@post = Post.find(params[:post_id])
@headline = @post.headlines.create(params[:headline].permit(:goto, :body))
redirect_to post_path(@post)
end
我确定在headlines_controller中定义存档是错误的,但我不知道该怎么做
def archive
@headlines_by_month = Headline.find(:all, :order => "created_at DESC").group_by { |headline| headline.created_at.strftime("%B") }
end
end
视图\ headlines_headlines.html.erb
<% @headlines_by_month.each do |monthname, headlines| %>
<%= monthname %>
<ul>
<% headlines.each do |headline| %>
<li><%= headline.body %></li>
<% end %>
</ul>
<% end %>
视图\帖子\ show.html.erb
<p>
<strong>Title:</strong>
<%= @post.title %>
</p>
<%= link_to 'Back', posts_path %>
<h2>Headlines</h2>
<%= render @post.headlines %>