NoMethodError in Recipe#index

I’m trying to teach myself Ruby on Rails, and doing the infamous
Cookbook as a starting point. I’m all set until the point when I go to
create of sumbit my recipe and I get this error:

NoMethodError in Recipe#index

You have a nil object when you didn’t expect it!
The error occured while evaluating nil.name

15: <% @recipes.each do |recipe| %>
16:


17: <%= link_to recipe.title, :action => “show”, :id => recipe.id
%>
18: <%= recipe.category.name %>
19: <%= recipe.date %>
20:
21: <% end %>

when I look in my MySQL database, the recipe is indeed in the db, but I
still get that error. Any help would be greatly appreciated.

Nick

On 7/8/06, Nick [email protected] wrote:

16:
17: <%= link_to recipe.title, :action => “show”, :id => recipe.id
%>
18: <%= recipe.category.name %>
19: <%= recipe.date %>
20:
21: <% end %>

when I look in my MySQL database, the recipe is indeed in the db, but I
still get that error. Any help would be greatly appreciated.

Looks to be complaining about the category being nil, do you have a
category assigned and saved for the recipe you’re trying to load?

When dealing with children’s attributes I find that I almost always
tag a conditional onto the end of the line, you just never know when
someone is going to do something stupid to the database (I work with a
bunch of people that know databases but don’t know Rails).

Something like:
<%= recipe.category.name if recipe.category %>
should help out with the NoMethodError until you can figure out why
exactly there isn’t a method in the first place :slight_smile:

Ta,
Chuck V.

Hi Nick,

Nick wrote:

You have a nil object when you didn’t expect it!
The error occured while evaluating nil.name

18:

<%= recipe.category.name %>

when I look in my MySQL database, the recipe
is indeed in the db, but I still get that error.

The error message looks to be telling you that Rails is evaluating
‘recipe.category’ as nil. One way that could happen is if you don’t
have
the belongs_to and has_many relations set up in the recipe and category
models.

hth,
Bill