首页 文章

以月/年红宝石显示帖子

提问于
浏览
0

不知道从哪里开始,所以这里就是..我正在 Build 一个小博客,其中显示每个帖子的日期,加班每月会有很多博客帖子,我想按月将它们组合在一起发表了 .

我想在视图中这样显示它

Archives

January 2013
February 2013
March 2013
etc

当我点击给定月份时,想法是它会将我带到那个月内发布的所有帖子 .

到目前为止,我可以按月和年分组所有帖子

@posts_by_month = Post.all.group_by { |post| post.created_at.strftime("%B %Y") }

在我看来,我然后这样渲染

<% @posts_by_month.each do |m| %>
  <%= m %>
<% end %>

在视图中返回此内容

["July 2013", [#<Post id: 1, title: "Ruby News", comments: "dsfdsfdsfdsfdsfds", category_id: 1, user_id: 1, created_at: "2013-07-26 07:10:25", updated_at: "2013-07-26 07:19:27", photo_file_name: "pf-7.jpg", photo_content_type: "image/jpeg", photo_file_size: 162495, photo_updated_at: "2013-07-26 07:19:26">]]

所以目前我有一个哈希,其中月/年是关键,然后我在阵列中的所有帖子,是正确的吗?

我要显示的只是月/年,然后点击那个月以获取该月的所有帖子

任何帮助赞赏

编辑

好吧,傻我,忘了关键/值配对的基本知识,我只有显示的日期

<% @posts_by_month.each do |m,p| %>
  <%= link_to m %>
<% end %>

现在我只需要能够点击链接查看该月的所有帖子

1 回答

  • 1

    你可以做到

    = link_to m, posts_path(:month => m)
    

    现在 posts#index ,根据 params[:month] 获取帖子

    if params[:month]
      date = Date.parse("1 #{params[:month]}")  # to get the first day of the month
      @posts = Post.where(:created_at => date..date.end_of_month)  # get posts for the month
    else
      @posts = Post.all
    end
    

相关问题