get model attribute dynamically in rails 3

允我心安 提交于 2019-12-23 07:21:56

问题


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


回答1:


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]



回答2:


Yet another approach:

attr = :first_name
@user.read_attribute attr  



回答3:


Try this

user = User.find(1)

then something like this should do what you require

user.send('field_name')



回答4:


Try this

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



回答5:


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)


来源:https://stackoverflow.com/questions/5996455/get-model-attribute-dynamically-in-rails-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!