开发者

How to access coloumn values from active record object?

开发者 https://www.devze.com 2023-03-14 07:07 出处:网络
I have an ActiveRecord object: @user = User.find_by_id(1) I want to access the name of the user from this object; how do I do it?

I have an ActiveRecord object:

@user = User.find_by_id(1)

I want to access the name of the user from this object; how do I do it?

@user.name  # Gives Error = No math开发者_高级运维od 'name'


If you use User.find instead of User.find_by_id and then perform .name on that, you should receive your output.

@user = User.find(1)
@user.name

But from not seeing your entire DB, it might be you're simply getting a no method because the field does not exist. In that case you should change the method name accordingly from:

@user.name # to ->
@user.first_name # or whatever the field is actually called


try

@user = User.find(1)

then

@user.name

find_by_id returns multiple records so you'd have to do

@user.first.name 

if you use find_by_id

0

精彩评论

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

关注公众号