0

祖先のRuby on Rails 3を使ってカテゴリツリーを作ろうとしています。私の_form.html.erb

<%= form_for(@category) do |f| %>
  <% if @category.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@category.errors.count, "error") %> prohibited this category from being saved:</h2>
      <ul>
        <% @category.errors.full_messages.each do |msg| %>
          <li><%= msg %></li>
        <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :title %><br />
    <%= f.text_field :title %>
  </div>
  <div class="field">
    <%= f.label :ancestry %><br />
    <%= f.collection_select :ancestry, Category.all(:order => "title"), :id, :title, :include_blank => true %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

私のindex.html.erb:

<ul id="menu">
  <% for category in @categories %>
    <li><%= link_to h(category.title), category %>
      <%= link_to "subcategory", new_category_path(:parent_id => category) %> |
      <%= link_to "Destroy", category, :confirm => "Are you sure?", :method => :delete %>
      <%= link_to 'Show', category %>
    </li>
  <% end %>
</ul>

すべてのカテゴリ ツリーを表示するようにインデックスを変更するにはどうすればよいですか? インデックスを次のように変更しようとしていました:

<ul id="menu">
  <% for category in @categories %>
    <li><%= category.subtree.all(:order => :title, :limit => 10) %>
      <%= link_to "subcategory", new_category_path(:parent_id => category) %> |
      <%= link_to "Destroy", category, :confirm => "Are you sure?", :method => :delete %>
      <%= link_to 'Show', category %>
    </li>       
  <% end %>
</ul>

しかし、変更後、タイトルだけを見ることができません:#<Category:0xb5fb731c>#<Category:0xb5fb6fc0>

4

1 に答える 1

4

ツリーの上から下まですべてのカテゴリのリストを表示したいとします。

次に、ancestry を使用すると、gem で指定されたrootsおよびメソッドに依存する必要があります。children例えば:

<ul id="menu">
  <% Category.roots.each do |category| %>
     <li> <%= link_to h(category.title), category %>
        # depending on the depth of your tree it is better to rely on an helper
        # to drill into the level of the tree
        <% unless category.children.empty? %>
           <ul id="sub-menu"> 
             <% category.children.each do |subcategory| %>
                <li> link_to h(subcategory.title), subcategory </li>
             <% end %>
           </ul>
        <% end %>
     </li>
  <% end %>
</ul>

再帰的アプローチに役立つ次のスニペットが見つかるかもしれません: http://dzone.com/snippets/acts-tree-category-display

于 2012-07-04T20:46:55.800 に答える