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

半腔热情 提交于 2020-01-04 20:38:40

问题


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>

回答1:


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 %>


来源:https://stackoverflow.com/questions/6204420/retrieving-username-with-find-by-idcomment-user-id-name-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!