动态获取Object的属性 [英] Dynamically get Object's attribute

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

问题描述

如何动态获取 activerecord 对象的属性值?

How do I dynamiclly get an attribute value for an activerecord object?

例如我有一个名为 attr_name 的变量.
我想做这样的事情:

for example I have a variable named attr_name.
I want to do something like this:

person = Person.find(1)
attr_name = "address"
address = person.<function_name>(attr_name)

可以使用哪个function_name?

推荐答案

要么使用 person.attributes[attr_name]person.read_attribute(att_name),甚至更短那么这是person[attr_name].

Either use person.attributes[attr_name] or person.read_attribute(att_name), or even shorter then this is person[attr_name].

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

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