RoR:attr_encrypted赋值不写?

时间:2011-03-22 18:39:42

标签: ruby-on-rails ruby-on-rails-3 activerecord encryption

我在RoR 3.0.5中使用attr_encrypted(v 1.2.0)来加密我不希望在我的数据库中显示为纯文本的凭据。当我更新加密字段时,它似乎没有保存到数据库中。

我的模特基本上是:

class Service << ActiveRecord::Base
    attr_encrypted :credentials_aux, :key => KEY, :attribute => 'encrypted_credentials', :encode => true, :marshal => true

  def credentials
    credentials_aux
  end

  def credentials=(c)
    h = {}.update(c)  # coerce HashWithIndifferentAccess to a vanilla hash
    credentials_aux = h
  end

  ...
end

(请注意,'credentials ='方法只是为了将Rails生成的HashWithIndifferentAccess强制转换为vanilla哈希。它还为我提供了一个插入调试打印输出来验证我的数据的地方。)

但是当我尝试通过控制台更新凭据时,它不需要:

>> s = Service.find(19)
=> #<Service id: 19, encrypted_credentials: "10VfHU7IkdrFb4Q6Hj18YtY81rbRp3sIuoVUl8CHNj88cq1XFo2...",>
>> s.credentials
=> {"user_id"=>"fred.flintstone", "password"=>"supersecret"}
>> s.credentials = {"user_id" => "barney.rubble", "password" => "notsosecret"}
=> {"user_id" => "barney.rubble", "password" => "notsosecret"}
>> s.credentials
=> {"user_id"=>"fred.flintstone", "password"=>"supersecret"}

为什么s.credentials没有更新到新值?

1 个答案:

答案 0 :(得分:3)

我相信你只是在你的“credentials =”方法中设置一个名为“credentials_aux”的局部变量,尝试明确地使用“self”

def credentials=(c)
  h = {}.update(c)  # coerce HashWithIndifferentAccess to a vanilla hash
  self.credentials_aux = h
end

我实际上是该项目的维护者,所以如果上面的修复不起作用,那么我将为此打开一张新票。