Kieran Klaassen
Kieran Klaassen

Reputation: 2202

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!

Upvotes: 46

Views: 54178

Answers (3)

Kaz
Kaz

Reputation: 179

In Rails 5, just attribute_name = "name" works

Upvotes: -3

Brent Matzelle
Brent Matzelle

Reputation: 4093

You can use either [] or read_attribute() but they are not equivalent. The safer method of access is using the [] method method because it will raise an ActiveModel::MissingAttributeError error if the attribute does not exist. The read_attribute method returns nil if the attribute does not exist.

Upvotes: 9

Frederick Cheung
Frederick Cheung

Reputation: 84114

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

Upvotes: 86

Related Questions