在Rails 3中动态获取模型属性 [英] get model attribute dynamically in rails 3

查看:58
本文介绍了在Rails 3中动态获取模型属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何动态地从模型对象获取属性?我将User对象的属性设置为字符串:

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)

我可以做类似u.get("user_id")

推荐答案

您可以尝试使用ActiveRecord模型实例(例如哈希).

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]

这篇关于在Rails 3中动态获取模型属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆