12

How can I get the attribute from the model object dynamically? I have the attribute of the User object as string:

u = User.find(1)

Can I do something like u.get("user_id")

4
  • I'm not totally understanding this question. What exactly are you trying to do? Commented May 13, 2011 at 18:58
  • Feel free to accept an answer from some given below if you're happy? Not close to what you need? Commented May 16, 2011 at 10:05
  • 1
    If you're talking about only ActiveRecord objects (as in the code example), you should probably be more explicit about it in the title and question. (I didn't realize this until I tried the answer.) The chosen answer treating the model as a hash only works for ActiveRecord objects and only for attributes that are columns. Commented Nov 15, 2014 at 17:51
  • I presume from context here that you mean to actually pull the attribute from the data store, otherwise it would be obvious to use u.user_id or one of several other simpler forms. Commented Nov 3, 2017 at 14:33

5 Answers 5

26

You could try using the ActiveRecord model instance like a hash.

u = User.find(1)
name = u[:name]
field = "first_name"
first_name = u[field]
Sign up to request clarification or add additional context in comments.

3 Comments

+1 This is the conventional approach when the attribute name isn't known in advance.
Note that this only works for attributes that are columns. It does not work for attributes made accessible through attr_accessor.
Yes, assuming "dynamically" means getting a fresh value of the attribute straight from the data store, then you must start by getting a fresh copy of the object from the data store, e.g. <active_record_class>.find(id) and then use the attribute value from the fresh copy as described here by @aditya-sanghi. The read_attribute method does not hit the database.
13

Yet another approach:

attr = :first_name
@user.read_attribute attr  

Comments

6

Try this

user = User.find(1)

then something like this should do what you require

user.send('field_name')

2 Comments

When working with enum attributes, this is the only way I've found that returns the field as a string rather than its raw integer value.
user.public_send('field_name') also works and is more secure
1

Try this

u = User.find(1)
attr = "first_name"
u.send(attr)

Comments

0

Not sure if I totally understand your questions. Try something like:

User.find(1).name

if you mean you only want to fetch from DB specific attribute you can do:

User.find(1,:select => :name)

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.