Recursive categories fetch and view I have categories and subcategories in my view. The code looks like this

&lt;ul&gt;
  &lt;% Category.roots.each do |category| %&gt;
  &lt;li class="col-md-2"&gt;
    &lt;a href="#"&gt;&lt;%= category.name %&gt;&lt;/a&gt;
    &lt;% if !category.children.empty? %&gt;
    &lt;ul&gt;
      &lt;%= category.decorate.draw_tree %&gt;
    &lt;/ul&gt;
    &lt;% end %&gt;
  &lt;/li&gt;
  &lt;% end %&gt;
&lt;/ul&gt;


I'm basically using a decorator to make it recursive

class CategoryDecorator &lt; Draper::Decorator

  delegate_all
  decorates :category

  def draw_tree

    children.inject("") do |memo, child|

      memo &lt;&lt; "&lt;li class=\"dir\"&gt;&lt;a href=\"#\"&gt;#{child.name}&lt;/a&gt;"
      memo &lt;&lt; "&lt;ul&gt;#{child.decorate.draw_tree}&lt;/ul&gt;" if not child.children.empty?
      memo &lt;&lt; "&lt;/li&gt;"

    end.html_safe

  end


end


It works fine. But I'm writing HTML inside a Ruby class and I don't like the idea, I'de like to keep it in the view. I tried to play with &amp;block to turn it like following

&lt;ul&gt;
  &lt;% Category.roots.each do |category| %&gt;
  &lt;li class="col-md-2"&gt;
    &lt;a href="#"&gt;&lt;%= category.name %&gt;&lt;/a&gt;
    &lt;% if !category.children.empty? %&gt;
    &lt;ul&gt;
      &lt;% category.decorate.draw_tree do |child| %&gt;

      &lt;li class="dir"&gt;&lt;a href="#"&gt;&lt;%= child.name %&gt;&lt;/a&gt;
      &lt;% if child.children.any %&gt;
        &lt;ul&gt;&lt;%= child.decorate.draw_tree %&gt;&lt;/ul&gt;"
      &lt;% end %&gt;
      &lt;/li&gt;"

      &lt;% end %&gt;
    &lt;/ul&gt;
    &lt;% end %&gt;
  &lt;/li&gt;
  &lt;% end %&gt;
&lt;/ul&gt;


Sadly, I couldn't make it work so far. I think I lack methodology here. How can I rewrite this code ?
Here's how I'd do it:

In your view, simply call a recursive method on each category:

&lt;ul&gt;
  &lt;% Category.roots.map do |category| %&gt;
     &lt;%= draw_tree(category) %&gt;
  &lt;% end %&gt;
&lt;/ul&gt;


And now in a helper file (app/helpers/category_helper.rb?), this is the "right" place to put HTML helpers. First, in pseudo-code:

def draw_tree(category)
  &lt;li class="col-md-2"&gt;
    &lt;a href="#"&gt;&lt;%= category.name %&gt;&lt;/a&gt;
    &lt;% category.children.each do |child| %&gt;
    &lt;ul&gt;
      &lt;%= draw_tree(child) %&gt;
    &lt;/ul&gt;
    &lt;% end %&gt;
  &lt;/li&gt;
end


Now, to actually make this work, rather than writing a string and calling #html_safe, a much cleaner (and generally safer) approach is to use content_tag. The end result is:

def draw_tree(category)
  content_tag(:li, class: "col-md-2") do
    link_to('#', category.name)
    category.children.map do |child|
      content_tag(:ul, draw_tree(child))
    end
  end
end


I haven't actually run the above code, so apologies if there's some small mistake. But hopefully you get the idea :)