【发布时间】: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