开发者

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.开发者_Go百科get("user_id")


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]


Yet another approach:

attr = :first_name
@user.read_attribute attr  


Try this

user = User.find(1)

then something like this should do what you require

user.send('field_name')


Try this

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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜