Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get model attribute dynamically in rails 3

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")

like image 751
ed1t Avatar asked May 13 '11 18:05

ed1t


3 Answers

Yet another approach:

attr = :first_name
@user.read_attribute attr  
like image 185
twmills Avatar answered Nov 03 '22 21:11

twmills


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]
like image 25
Aditya Sanghi Avatar answered Nov 03 '22 21:11

Aditya Sanghi


Try this

user = User.find(1)

then something like this should do what you require

user.send('field_name')
like image 6
Scott Avatar answered Nov 03 '22 20:11

Scott