ruby-on-railsruby-on-rails-3acts-as-tree

Error when trying to display parent name using acts_as_tree


I am using the acts as tree gem to create a Category model:

  1 class Category < ActiveRecord::Base
  2   include ActsAsTree
  3   attr_accessible :name
  4 
  5   acts_as_tree order: "name"
  6 end

In one of my views, I am trying to display the category's parent's name:

 12 <% @categories.each do |category| %>
 13   <tr>
 14     <td><%= category.name %></td>
 15     <td><%= category.parent.name %></td>
 16     <td><%= link_to 'Show', category %></td>
 17     <td><%= link_to 'Edit', edit_category_path(category) %></td>
 18     <td><%= link_to 'Destroy', category, method: :delete, data: { confirm: '
 19   </tr>
 20 <% end %>

However, I am getting an error when accessing the view:

undefined method `name' for nil:NilClass

I can, however, display category.parent_id successfully.

Any ideas?


Solution

  • You have dirty data in your database. you are getting nil when you call category.parent and when you call name method on category.parent you are actually calling name method on nil and hence it is giving an error undefined methodname' for nil:NilClass`

    This happens when you have data like following

    id  name      parent_id
    2   child1     1     
    3   child2     1     
    

    Now i have above two data in my table, here you can see parent for both the record is 1, so there must be have a record with id 1.

    <%
       child = Model.find 2
       child.parent_id #This gives you `1`
       child.parent #This gives you `nil`
       child.parent.name #This gives you error undefined method `name' for nil:NilClass
     %>