47

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!

3 Answers 3

86

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

Sign up to request clarification or add additional context in comments.

6 Comments

I concur that it is better to avoid send. However if you are accessing an association rather than a plain attribute, it seems like send is your best bet.
Can you tell me why I should avoid send? I'm afraid I have to use it.
@user2041318 with send you need to be extra sure that you've been passed an actual attribute name (rather than, for example, 'destroy')
If there's a wrapper plugin over the attribute (like, carrierwave), first two solutions will get u string instead of Carrierwave object. If u want attribute including wrapper class, use this user.read_attribute_for_serialization(attribute_name) (it works, though I dont know what that fuction is for)
user[attribute_name] are different user.send(attribute_name). user[attr_name] => get from db field, user.send(attr_name) => get from model
|
10

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.

4 Comments

The read_attribute method is still present in ActiveRecord 5 and I can't find any hints about it being deprecated.
Read this APIdock page which states the following: "This method is deprecated or moved on the latest stable version. The last existing version (v2.3.8) is shown here."
It was just moved to the module ActiveRecord::AttributeMethods::Read and is still present.
I removed the notes about the function being deprecated and added some new notes on the differences between the [] and read_attribute functions.
-3

In Rails 5, just attribute_name = "name" works

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.