views:

231

answers:

1

In my Rails application I have a User model (more or less built by RESTful Authentication), and several other models belonging to the user. So let's say, for example:

user has_many :posts

post belongs_to :user

Anywhere in the users resource I can access the user variables as I would expect. @user.name, @user.email, @user.login, etc. all return the expected object.

However, I can't seem to access any of these attributes from any other resource (in this example, posts) without it returning nil (nil rather than a NoMethodError).

Why is this? It seems even stranger to me that I can call current_user just fine, as in current_user.name, current_user.email, but not for the user in question.

+1  A: 

There are two users you could be talking about here.
1) the currently logged in user
2) the user who the post belongs to

the currently logged in user should be able to be accessed through the current_user. the user who the post belongs to will need to be set in the Posts controller:

@user = Users.find(@post.user_id)

or

@user = @post.user
Thanks for the response. Let's say I'm trying to access the user's name who the post belongs to from Posts/show. The name would be @user.name in the Users resource. And for show in the Posts controller currently: @post = Post.find(params[:id], @user).
Bryan Woods
If I were trying to access the name of the user who added the post I would (in the PostsController) set the user: @post = Post.find(params[:id]), then set the user @user = @post.user. Then in the view: Posted by <%= @user.name %>. HTH
It's strange, you're saying exactly what I would expect, but the problem is persisting. I'm beginning to wonder what might be going on under the hood that I'm not noticing.
Bryan Woods
Have you added a user_id column to your posts table? if so, does that column have any data in it?