用find_by_id(comment.user_id).name检索不到用户名 [英] retrieving username with find_by_id(comment.user_id).name not working

查看:364
本文介绍了用find_by_id(comment.user_id).name检索不到用户名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用


,我试图检索用户名插入到使用rails的博客文章的评论b $ b

 <%= comment.user_id%>

它会给我一个id,但如果我尝试和检索用户,然后调用它的名称返回nil类

 <%= User.find_by_id(comment.user_id).name%> 

为什么这不起作用

if

 #<用户:000x00000182fe48> 


解决方案

id 并返回(Ruby)对象的 id (即 object_id )而不是记录的 id



尝试调用 User.find .user_id).name 代替。或者,更好的是: comment.user.name



上面应该回答你的问题,要做的是:

在控制器中:

$ $ $ $ $ $ $ c $ @user_name = @ comment.user.name

在视图中:

 <%= @user_name%> 


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

这篇关于用find_by_id(comment.user_id).name检索不到用户名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆