【问题标题】:Display navigation with infinite sub-entries in array在数组中显示具有无限子条目的导航
【发布时间】:2012-01-22 20:33:56
【问题描述】:

我有一个模型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 上遇到了类似的问题,这很好用,但现在我需要一个下拉列表,其中包含在其层次结构中显示的所有类别。这真的让我很困惑,我根本不明白!我想要包括孩子在内的顶级类别,孩子们应该包括她的孩子,...我怎样才能在数组中显示这个?

我需要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 %>

【问题讨论】:

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


    【解决方案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 )
    

    【讨论】:

    • 我不得不稍微修改一下,因为我想使用集合选择,而这不能很好地处理ArrayHash,所以我改用了Struct。请参阅帖子编辑,...但基本上您的回答对我有很大帮助!
    【解决方案2】:

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

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

    如果你想要它以选择形式,这里有一个链接帖子如何做到这一点,我用谷歌搜索了它,我自己没有尝试过。 http://www.rabbitcreative.com/2008/02/01/turn-an-acts_as_tree-structure-into-a-select-drop-down/

    【讨论】:

      猜你喜欢
      • 2012-02-10
      • 1970-01-01
      • 1970-01-01
      • 2017-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-26
      相关资源
      最近更新 更多