NoMethodError when trying to reference a column from a different table - Ruby on Rails -


i have 2 tables head , 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 view file

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

at runtime following error:

undefined method `name_subcategory' nil:nilclass

i'm pretty new rails think has not making proper relationships between tables i'm pretty stumped exact problem. tried research error seems broad , can caused wide range of problems , i'm having trouble pinpointing i'm going wrong.

i hope here can help!

edit i'm trying achieve: each head contains many categories , i'm trying print out head associated particular category (i know naming strange, team project i've joined)

ideally relation should

belongs_to :head   #note: head singlular 

as marek lipka said, 1 of category have nil head.

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

or

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

remember change method call head, if change relation


Comments