How to view navigation with infinit sub entries?

2019-09-02 10:59发布

问题:

Ive got a simple Model called Category. The model is has three fields : name:string, parent_id:integer and of cause an id! The parent_id is an self referential association:

has_many :children, :class_name => 'Category', :foreign_key => 'parent_id'
belongs_to :parent, :class_name => 'Category', :foreign_key => 'parent_id'

So every Category can have subcategories and on and on and on,... This isnt a problem at the database but when it comes to the view Im getting confused!

I dont get how I can loop through each categories children and those childrens children,...

回答1:

Assuming you had a partial called category you could do something like this

%h2= category.name
%ul
  - category.children.each do |child|
    %li
      = render :partial => 'category', :object => child

I've used haml but it would be about the same in erb.