0

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?

AlexBrand
  • 11,971
  • 20
  • 87
  • 132

1 Answers1

1

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
 %>
Salil
  • 46,566
  • 21
  • 122
  • 156
  • I don't think so... When calling child.parent I get the parent category instance: `#` – AlexBrand Oct 08 '12 at 04:25
  • You are iterating loop over `@categories` so if any category having dirty parent it will throw error.....i am not saying all the data is dirty but single record can raise a error..........change `<%= category.parent.name %>` to `<%= category.parent ? category.parent.name : category.parent_id %>` to check the dirty data – Salil Oct 08 '12 at 04:30
  • You're right. I think it has to do with the fact that the root category does not have a parent. But what can I do about this? – AlexBrand Oct 08 '12 at 04:34
  • I think `<%= category.parent.name if category.parent %>` will solve a problem. For a root category it will display nothing. – Salil Oct 08 '12 at 04:41