Eyal R
Eyal R

Reputation: 293

Dynamically get attribute value of ActiveRecord object

How do I dynamically get an attribute value of an ActiveRecord object?

for example, I have a variable named attr_name.
I want to do something like this:

person = Person.find(1)
attr_name = 'address'
# address = person.<function_name>(attr_name)

which function_name can be used?

Upvotes: 17

Views: 22505

Answers (3)

Abram
Abram

Reputation: 41884

If doing this using send

address = person.send("function_name" + "attr_name")

Upvotes: 1

Samnang
Samnang

Reputation: 5616

Either use person.attributes[attr_name] or person.read_attribute(att_name), or even shorter then this is person[attr_name].

Upvotes: 35

Syed Aslam
Syed Aslam

Reputation: 8807

send is the method you're looking for.

Upvotes: 5

Related Questions