Rails 3 - Record.send无效

时间:2012-10-15 23:20:32

标签: ruby-on-rails-3 activerecord

我有一个显示所有客户的视图。我有一个支持此视图的Customer模型。模型中有一种方法可以将属性从“”更改为人名首字母“jh”。这是方法。

def print(item, attribute)
  value = item.send(attribute)
  if(value.blank?)
    item.send(attribute + '=', "jh")
  else
    item.send(attribute + '=', "")
  end
end

当我从控制台运行此代码时,它运行正常。当我在应用程序中尝试它时,没有任何变化。我得到了我期望的正确“价值”,但它永远不会变成空字符串。我相信我在这里遗漏了一些简单的东西,但请帮忙。谢谢。

1 个答案:

答案 0 :(得分:1)

我没有看到这个代码有任何问题,我在普通的ruby对象和ActiveRecord模型上都尝试了它,并且都按预期工作。因此,我怀疑发生了一些特定于您的代码的有趣内容。

我建议在任何情况下,不应该通过字符串连接构造一个setter,而应该使用Ruby的原生instance_variable_set

def print(item, attribute)
  value = item.send(attribute)
  if(value.blank?)
    item.instance_variable_set("@#{attribute}", "jh")
  else
    item.instance_variable_set("@#{attribute}", "")
  end
end

使用此方法的一个警告是,如果以前都不存在,它将创建一个实例变量。