Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get attribute of ActiveRecord object by string

It is probably a really simple thing but can't find a solution.

I have an ActiveRecord object and want to get an attribute like this:

attribute_name = "name" user = User.find(1) user.get_attribute_by_name(attribute_name) => "John" 

Thanks!

like image 287
Kieran Klaassen Avatar asked Aug 04 '12 13:08

Kieran Klaassen


1 Answers

All of these should work:

user[attribute_name] user.read_attribute(attribute_name) user.send(attribute_name) 

Personally I wouldn't use send in this case. When available, prefer public_send to send

like image 169
Frederick Cheung Avatar answered Sep 22 '22 16:09

Frederick Cheung