5

やあみんな。通常のCRUDアクションを使用して簡単なブログアプリを作成しました。また、PostControllerに「アーカイブ」と呼ばれる新しいアクションと関連するビューを追加しました。このビューでは、すべてのブログ投稿を元に戻し、月ごとにグループ化して、次のような形式で表示します。

March
<ul>
    <li>Hello World</li>
    <li>Blah blah</li>
    <li>Nothing to see here</li>
    <li>Test post...</li>
</ul>

Febuary
<ul>
    <li>My hangover sucks</li>
    ... etc ...

私はこれを行うための最良の方法を私の人生のために理解することはできません。Postモデルに通常titlecontentcreated_atなどのフィールドがあると仮定すると、誰かがロジック/コードを手伝ってくれるでしょうか?私はRoRを初めて使用するので、ご容赦ください:)

4

2 に答える 2

31

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" => [#<Post 0xb5c836a0>,#<Post 0xb5443a0>],
  # 'March' => [#<Post 0x43443a0>] }
  @posts_by_month = Posts.find(:all).group_by { |post| post.created_at.strftime("%B") }
end

ビュー テンプレート:

<% @posts_by_month.each do |monthname, posts| %>
<%= monthname %>
<ul>
   <% posts.each do |post| %>
     <li><%= post.title %></li>
   <% end %>
</ul>
<% end %>
于 2009-07-03T19:46:51.407 に答える
7

@マキシミリアーノ・グズマン

いい答えです!Rails コミュニティに価値をもたらしてくれてありがとう。How to Create a Blog Archive with Railsに私の元のソースを含めます。ブログ投稿に基づいて、Rails の新しい開発者向けに、いくつかの提案を追加します。

まず、Active RecordsのPosts.allメソッドを使用して Post 結果セットを返し、速度と相互運用性を向上させます。Posts.find (:all)メソッドには予期しない問題があることが知られています。

最後に、同じ要領で、ActiveRecord コア拡張機能の begin_of_month メソッドを使用します。starting_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

<div class="archives">
    <h2>Blog Archive</h2>

    <% @post_months.sort.reverse.each do |month, posts| %>
    <h3><%=h month.strftime("%B %Y") %></h3>
    <ul>
        <% for post in posts %>
        <li><%=h link_to post.title, post_path(post) %></li>
        <% end %>
    </ul>
    <% end %>
</div>

Rails へようこそ!

于 2010-10-17T04:50:31.730 に答える