【问题标题】:How to create Category tree using ancestry Ruby on Rails 3如何使用祖先 Ruby on Rails 3 创建类别树
【发布时间】:2012-07-04 18:59:04
【问题描述】:

我正在尝试使用祖先 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>

但更改后无法看到标题:#&lt;Category:0xb5fb731c&gt;#&lt;Category:0xb5fb6fc0&gt;

【问题讨论】:

  • 您是在问如何通过类别树递归显示所有孩子?
  • 是的,这就是我需要的

标签: ruby-on-rails ruby tree categories ancestry


【解决方案1】:

我假设您想要显示从树的顶部到底部的所有类别的列表。

然后使用祖先,您必须依赖 gem 中给出的 rootschildren 方法。 例如:

<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>

您可能会发现以下 sn-p 对于递归方法很有用: http://dzone.com/snippets/acts-tree-category-display

【讨论】:

  • 我还是有一些问题。现在我可以看到类别的名称,但只是根和子类别而已。我只能看到 CategoryLevel1 看不到 Level2。根 -CategoryLevel1 --CategoryLevel2
  • @user1502296 - 上面的代码,只显示根和第一层子级。如果您想要递归版本,请查看我在上面粘贴的 sn-ps。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多