Ruby on Rails:按月分组博客文章
嗨伙计们。 我用通常的CRUD动作创建了一个简单的博客应用程序。 我还在PostController中添加了一个名为“archive”的新动作和一个相关视图。 在这个视图中,我想带回所有博客文章并按月分组,以这种格式显示它们:
March - Hello World
- Blah blah
- Nothing to see here
- Test post...
Febuary - My hangover sucks
... etc ...
我不能为我的生活找出最好的方法来做到这一点。 假设Post模型具有通常的title
, content
, created_at
等字段,有人可以帮我解决逻辑/代码吗? 我对RoR很新,所以请耐心等待:)
group_by是一个很棒的方法:
控制器:
def archive #this will return a hash in which the month names are the keys, #and the values are arrays of the posts belonging to such months #something like: #{ "February" => [#,# ], # 'March' => [# ] } @posts_by_month = Posts.find(:all).group_by { |post| post.created_at.strftime("%B") } end
查看模板:
<% @posts_by_month.each do |monthname, posts| %> <%= monthname %> <% posts.each do |post| %> - <%= post.title %>
<% end %>
<% end %>
@Maximiliano Guzman
好答案! 感谢您为Rails社区增加价值。 我将原始资料包含在如何使用Rails创建博客存档中 ,以防万一我对作者的推理进行了抨击。 根据博客文章,对于Rails的新开发者,我会添加一些建议。
首先,使用Active Records Posts.all方法返回Post结果集,以提高速度和互操作性。 已知Posts.find(:all)方法存在无法预料的问题。
最后,按照相同的方式,使用ActiveRecord核心扩展中的beginning_of_month方法。 我发现begin_of_month比strftime(“%B”)更具可读性。 当然,选择是你的。
以下是这些建议的示例。 有关更多详细信息,请参阅原始博文:
控制器/ archives_controller.rb
def index @posts = Post.all(:select => "title, id, posted_at", :order => "posted_at DESC") @post_months = @posts.group_by { |t| t.posted_at.beginning_of_month } end
意见/档案馆/ indext.html.erb
Blog Archive
<% @post_months.sort.reverse.each do |month, posts| %> <%=h month.strftime("%B %Y") %>
<% for post in posts %> - <%=h link_to post.title, post_path(post) %>
<% end %>
<% end %>
祝你好运,欢迎来到Rails!