Reputation: 263
I'm trying to retrieve a user name to insert into a comment on a blog post using rails
if I use
<%= comment.user_id %>"
it will give me an id but if I try and retrieve the user then call the name it return nil class
<%= User.find_by_id(comment.user_id).name %>"
why is this not working
if I leave .name off it returns a space in memory.
#<User:000x00000182fe48>
Upvotes: 2
Views: 2629
Reputation: 25994
Most likely, the dynamic finder is getting confused by the id
and is returning the (Ruby) object's id
(i.e. object_id
) instead of the record's id
.
Try calling User.find(comment.user_id).name
instead. Or, better: comment.user.name
.
The above should answer your question, but what you really want to do is:
In the controller:
@user_name = @comment.user.name
In the view:
<%= @user_name %>
Upvotes: 5