Reputation: 293
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
Reputation: 41884
If doing this using send
address = person.send("function_name" + "attr_name")
Upvotes: 1
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