Ruby-on-rails 通过字符串获取 ActiveRecord 对象的属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11808949/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 03:48:31  来源:igfitidea点击:

get attribute of ActiveRecord object by string

ruby-on-railsruby-on-rails-3

提问by Kieran Klaassen

It is probably a really simple thing but can't find a solution.

这可能是一件非常简单的事情,但找不到解决方案。

I have an ActiveRecord object and want to get an attribute like this:

我有一个 ActiveRecord 对象,想要获得这样的属性:

attribute_name = "name"
user = User.find(1)
user.get_attribute_by_name(attribute_name) => "John"

Thanks!

谢谢!

回答by Frederick Cheung

All of these should work:

所有这些都应该有效:

user[attribute_name]
user.read_attribute(attribute_name)
user.send(attribute_name)

Personally I wouldn't use sendin this case. When available, prefer public_sendto send

我个人不会send在这种情况下使用。可用时,更喜欢public_send发送

回答by Brent Matzelle

You can use either []or read_attribute()but they are not equivalent. The safer method of access is using the [] methodmethod because it will raise an ActiveModel::MissingAttributeErrorerror if the attribute does not exist. The read_attribute methodreturns nilif the attribute does not exist.

您可以使用[]or ,read_attribute()它们不是等价的。更安全的访问方法是使用[] 方法方法,因为ActiveModel::MissingAttributeError如果该属性不存在,它将引发错误。该read_attribute方法返回nil如果属性不存在。

回答by Kaz

In Rails 5, just attribute_name = "name"works

在 Rails 5 中,attribute_name = "name"正常工作