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?
You have dirty data in your database. you are getting
nilwhen you callcategory.parentand when you callnamemethod oncategory.parentyou are actually callingnamemethod onniland hence it is giving an errorundefined methodname' for nil:NilClass`This happens when you have data like following
Now i have above two data in my table, here you can see
parentfor both the record is1, so there must be have a record with id1.