如何将属性名称转换为字符串?

时间:2010-03-28 16:42:19

标签: ruby-on-rails ruby activerecord

假设我们有一些基本的AR模型。

class User < ActiveRecord::Base
  attr_accessible :firstname, :lastname, :email
end

...

some_helper_method(attrib)
  ...
def  

现在我想将someuser.firstname传递给helper,我想得到值和属性名称,例如:

some_helper_method(someuser.firstname)
> "firstname: Joe" 

some_helper_method(someuser.lastname)
> "lastname: Doe" 

2 个答案:

答案 0 :(得分:1)

我不确定你要做什么,但这是一个可能的解决方案:

def some_helper_method(object, attr)
  "#{attr}: #{object.send(attr)}"
end

现在您可以按如下方式调用帮助程序:

some_helper_method(someuser, :firstname)
# => "firstname: Joe"

答案 1 :(得分:0)

您不能按照问题中描述的方式进行操作。原因很简单:someuser.lastname返回一个字符串,这是姓氏 但是你不知道这个字符串来自哪里。你无法知道这是姓氏。

一种解决方案是执行以下辅助方法:

def some_helper_method(user, attribute)
    "#{attribute.to_s}: #{user.send(attribute)}"
end

然后使用以下方法调用此方法:

some_helper_method someuser, :lastname

该方法将调用someuser.lastname并返回属性的名称及其值。

相关问题