开发者

retrieving username with find_by_id(comment.user_id).name not working

开发者 https://www.devze.com 2023-03-09 16:08 出处:网络
I\'m trying to retrieve a user name to开发者_如何学JAVA insert into a comment on a blog post using rails

I'm trying to retrieve a user name to开发者_如何学JAVA 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 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 %>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号