Yugal Jindle
Yugal Jindle

Reputation: 45646

How to access coloumn values from active record object?

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 mathod 'name'

Upvotes: 0

Views: 4151

Answers (2)

siame
siame

Reputation: 8657

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

Upvotes: 1

John Beynon
John Beynon

Reputation: 37507

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

Upvotes: 1

Related Questions