0

I am trying to convert a nested hash tree to nested HTML list. So far I've created Post and Tag model and implemented hierarchy to the Tag model using Closure Tree .

Following is the helper method I've found from another post to make a recursive method to render hash to a nested set of list:

def hash_list_tag(hash)
  html = content_tag(:ul) {
    ul_contents = ""
    ul_contents << content_tag(:li, hash[:parent])
    hash[:children].each do |child|
      ul_contents << hash_list_tag(child)
    end

    ul_contents.html_safe
  }.html_safe
end

I just inserted this code to my helper section (application_helper.rb) without changing anything.

Afterwards, I embedded the following inside the view page(index.html.erb) to render a hash to a nested HTML list:

<div>
  <% hash_list_tag Tag.hash_tree do |tag| %>
    <%= link_to tag.name, tag_path(tag.name) %>
  <% end %>
</div>

However, I received this error:

ActionView::Template::Error (undefined method `each' for nil:NilClass):
    1: 
    2: 
    3: <div>
    4:   <% hash_list_tag Tag.hash_tree do |tag| %>
    5:     <%= link_to tag.name, tag_path(tag.name) %>
    6:   <% end %>
    7: </div>
  app/helpers/application_helper.rb:14:in `block in hash_list_tag'
  app/helpers/application_helper.rb:11:in `hash_list_tag'
  app/views/posts/index.html.erb:4:in `_app_views_posts_index_html_erb__1316616690179183751_70207605533880'
1
  • Sadly I'm not at a level to write my own helper methods, I found this helper method from another post. This is the link <stackoverflow.com/questions/14904772/…>. I'll greatly appreciate if you could help me what I should do to fix this or advise me if there's other way to call the descendants of root nodes. Commented Jan 26, 2014 at 2:30

2 Answers 2

0

When you do

hash[:children].each do |child|

and there are no children, the result is a nil, which has no method called each. (Read the error message). So you need to check for this case:

if !(hash[:children].nil?)
  hash[:children].each do |child|
Sign up to request clarification or add additional context in comments.

1 Comment

This removed the error, but I don't see my list on the index page. I'm double checked from 'rails console' that Tag.hash_tree generates nested hash.
0

With closure tree you dont get hash with :parent and :children keys. Below code will solve your issue.

html = content_tag(:ul) {
    ul_contents = ""
    hash.each do |key, value|
      ul_contents << content_tag(:li, key)
      if value.present?
        value.each do |child|
          ul_contents << hash_list_tag(child)
        end
      end
    end

    ul_contents.html_safe
  }.html_safe

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.