get model attribute dynamically in rails 3

2019-06-15 23:49发布

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

5条回答
▲ chillily
2楼-- · 2019-06-16 00:14

Try this

user = User.find(1)

then something like this should do what you require

user.send('field_name')
查看更多
SAY GOODBYE
3楼-- · 2019-06-16 00:24

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)
查看更多
虎瘦雄心在
4楼-- · 2019-06-16 00:28

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]
查看更多
太酷不给撩
5楼-- · 2019-06-16 00:34

Yet another approach:

attr = :first_name
@user.read_attribute attr  
查看更多
Lonely孤独者°
6楼-- · 2019-06-16 00:34

Try this

u = User.find(1)
attr = "first_name"
u.send(attr)
查看更多
登录 后发表回答