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>
Most likely, the dynamic finder is getting confused by the
idand is returning the (Ruby) object’sid(i.e.object_id) instead of the record’sid.Try calling
User.find(comment.user_id).nameinstead. Or, better:comment.user.name.The above should answer your question, but what you really want to do is:
In the controller:
In the view: