views:

37

answers:

3
Showing app/views/posts/_post.html.erb where line #4 raised:

undefined method `name' for nil:NilClass

Extracted source (around line #4):

1: <p>
2:  <b>Post Content:</b>
3:  <%=h post.content %> by 
4:  <%=h post.author.name %>
5: </p>

Here is my posts model:

class Post < ActiveRecord::Base
  belongs_to :board
  belongs_to :author, :class_name => "User"
end

The weird thing is, if I comment out post.author.name, it works. And.... I tried it in the console, it works fine:

>> post
=> #<Post id: 1, content: "trying", user_id: 2, created_at: "2010-06-22 04:24:53", updated_at: "2010-06-22 04:24:53">
>> post.author
=> #<User id: 2, login: "[email protected]", name: "test1",....
>> post.author.name
=> "test1"

In fact, if I change post.author.name to post.user_id, it displays the correct id (which is 2)....

What is the problem??

Thanks a lot.

A: 

Two things:

  1. Are you sure the post you're checking in the console is the same one that's being accessed in the view? Maybe you're doing something like post = Post.first and it's not the right one?
  2. In the extracted view source, you're referencing a non-instance variable. Are you assigning post elsewhere in the view (like a loop)? If not, changing it to @post might do it. Though this is unlikely, since the error message would likely be different.
rspeicher
Yes, that's my only post, but I am looping through all the posts by calling a partial. >> Post.all => [#<Post id: 1, content: "trying", user_id: 2, created_at: "2010-06-22 04:24:53", updated_at: "2010-06-22 04:24:53">]
+1  A: 

Try to specify value of :foreign_key

Bohdan Pohorilets
A: 

You have to also specify the :foreign_key => "user_id". Rails will, by default, use the symbol passed to belongs_to to derive the foreign key field. In your case, even though you have specified the class name, it will look for author_id as the foreign key. The class_name option tells Rails what kind of object to expect.

Nick Stamas