17

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?

3 Answers 3

35

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

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

4 Comments

This is the safest and correct way. Note that this will only work for attributes, not other methods, or associations.
Unable to get attributes or methods with the object[symbol or string] syntax. Create a simple class and make some variable or method publicly accessible with the dot syntax first to see it works, then try to access it via symbol or string.. no worky.
``` class Foo def initialize @foo = 'foo name' @bar = 'bar name' end def foo @foo end end foo = Foo.new foo[:foo] ```
@NickRes that is activerecord only.
5

send is the method you're looking for.

2 Comments

depending where the function names comes from, this could be quite dangerous, so I would not do that
If you're just getting the attribute value dynamically then I would definitely use something like [] or attributes[] or read_attribute. It's clearer and less dangerous. But, to do really dynamic things, you'll need send.
1

If doing this using send

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

1 Comment

If you're just getting the attribute value dynamically then I would definitely use something like [] or attributes[] or read_attribute. It's clearer and less dangerous. But, to do really dynamic things, you'll need send.

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.