I have a Model Category which has name:string categoryId:integer parent_id:integer the categoryId doesnt matter in this case I know that it doesnt match the RoR naming convention but I have good reasons for this… Model looks like this:
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")
I had a similar problem with the view here and this works well but now i need a dropdown with all the categories displayed in its hierarchie. This is really messing with me i simply dont get it! I want the top categories including the children and the children should include her children,… How can I display this in an array?
I need these data for a collection_select which should display the whole navigation but not on one area I want to display it like this:
Top-Category1
---Sub-Category1
------Sub-Category1-1
------Sub-Category1-2
---Sub-Category2
Top-Category2
---Sub-Category1
Can anyone help me?
// Solved it like this:
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
I defined Struct::Category in ApplicationHelper which is included in ApplicationController. Then I used this to display it in form:
<%= f.collection_select :category_id, Category.recursive_categories(Category.top_categories), :id, :name %>
Fairly simple recursion to get the choices array ready for
select: