显示数组中无限子条目的导航

时间:2012-01-22 20:33:57

标签: ruby-on-rails ruby ruby-on-rails-3 navigation

我有一个模型Category name:string categoryId:integer parent_id:integer categoryId在这种情况下并不重要我知道它与RoR命名约定不符,但我有充分的理由...模型看起来像这样:

has_many :children, :class_name => 'Category', :foreign_key => 'parent_id'
belongs_to :parent, :class_name => 'Category', :foreign_key => 'parent_id'
....
...
..
scope :top_categories, where("parent_id IS NULL")

我在视图here中遇到了类似的问题,但效果很好但现在我需要一个下拉列表,其所有类别都显示在其hierarchie中。这真的搞砸了我,我根本得不到它!我希望包括孩子和孩子在内的顶级类别应该包括她的孩子,...我怎样才能在数组中显示它?

我需要collection_select的这些数据,这些数据应该显示整个导航,而不是我想要显示的一个区域:

Top-Category1
---Sub-Category1
------Sub-Category1-1
------Sub-Category1-2
---Sub-Category2
Top-Category2
---Sub-Category1

任何人都可以帮助我吗?

//像这样解决了:

  def self.recursive_categories(categories, prefix='')
            c = []
            categories.collect do |cat|
                    current = Struct::Category.new
                    current.id = cat.id
                    current.name =  "#{prefix}#{cat.name}"
                    c << current
                    if cat.children
                           c += recursive_categories( cat.children, prefix + '--' )
                    end
            end
            c
  end

我在ApplicationHelper中定义了Struct::Category,它包含在ApplicationController中。然后我用它来表格形式:

<%= f.collection_select :category_id, Category.recursive_categories(Category.top_categories), :id, :name %>

2 个答案:

答案 0 :(得分:1)

使select准备好选择数组的相当简单的递归:

# in a helper
def recursive_options categories, prefix=''
  c = []
  categories.collect do |cat|
    c << [ prefix + cat.name, cat.id ]
    if cat.categories
      c += recursive_options( cat.categories, prefix + '--' )
    end
  end
  c
end

# then in your view somewhere
<%= f.select :category_id, recursive_options( Category.top_categories )

答案 1 :(得分:0)

这会将所有类别显示为链接

module CategoriesHelper
  def render_categories(categories, level = 1)
    buffer = ""
    categories.each do |category|
      buffer +=link_to category.name, "#"
      buffer +="<br/>"
      unless category.sub_categories.blank?
        buffer +="&nbsp;&nbsp;&nbsp;&nbsp;"*level
        buffer +=render_categories(category.sub_categories, level+=1)
      end
    end
    return buffer
  end
end
在您的视图中

<%= render_categories(Category.top_level).html_safe %>

如果你想选择它的形式,这里有一个链接帖子怎么做,我google了它,没有自己尝试。 http://www.rabbitcreative.com/2008/02/01/turn-an-acts_as_tree-structure-into-a-select-drop-down/