Question

I have two tables Head and Category

In head.rb

has_many :categories
attr_accessible :name_subcategory, :quote, :statement

In category.rb

belongs_to :heads
attr_accessible :image_url, :string, :title, :show_on_home_page, :show_on_category_page, :show_in_footer, :float_subcategory, :name_subcategory

In my view file

<% @category.each do |category| %>
<%= category.heads.name_subcategory %>
<% end %>

At runtime I get the following error:

undefined method `name_subcategory' for nil:NilClass

I'm pretty new to rails so I think this has something to do with not making the proper relationships between the tables but I'm pretty stumped as to the exact problem. I tried to research the error but it seems to be very broad and can be caused by a wide range of problems and I'm having trouble pinpointing exactly where I'm going wrong.

I hope someone here can help!

Edit What I'm trying to achieve: Each head contains many categories and I'm trying to print out the head associated with a particular category (I know the naming is strange, this is a team project that I've only just joined)

Was it helpful?

Solution

Ideally the relation should be

belongs_to :head   #note: head is singlular

As Marek Lipka said, one of the category could have a nil head. So you could do

<%= category.heads.name_subcategory if category.heads %>

OR

<%= category.heads.try :name_subcategory %>

Remember to change the method call to head, if you change the relation

OTHER TIPS

The reason you get this error is that Category#head for at least one Category record returns nil.

The way to fix this error depends on what you want from this association. If you want every Category record has its Head associated, you may use validations. You should also name association properly, belongs_to association name should be singular. Example is given here:

class Category < ActiveRecord::Base
  belongs_to :head
  validates_presence_of :head
end

You may on the other hand have an error in setting the association. Given head variable contains reference to Head instance and category is Category instance, you should set association with:

category.head = head
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top