多次创建 before_save 调用

珍娜

我的模型中有一个 before_save 回调,它在将 2 个字段保存到数据库之前对其进行加密。

class Account < ActiveRecord::Base
  before_save :encrypt_credentials, if: "!username.blank? && !password.blank?"

  def encrypt_credentials
    crypt = ActiveSupport::MessageEncryptor.new(ENV['KEY'])
    self.username = crypt.encrypt_and_sign(username)
    self.password = crypt.encrypt_and_sign(password)
  end

  def decrypted_username
    crypt = ActiveSupport::MessageEncryptor.new(ENV['KEY'])
    crypt.decrypt_and_verify(username)
  end

  def decrypted_password
    crypt = ActiveSupport::MessageEncryptor.new(ENV['KEY'])
    crypt.decrypt_and_verify(password)
  end
end

这种情况非常类似于多次运行before_save的Devise模型?. 当我调用 Model.create!(...) - 其中包括需要加密的 2 个字段时, before_save 被调用两次,最终在被加密的字段中结束。

Account.create!(
{
  username: ENV['USERNAME'],
  password: ENV['PASSWORD']
})

为什么 before_save 被多次调用?我不喜欢上面链接的帖子的解决方案,我不想先新建/构建然后保存。

珍娜

这是用户错误:( 在调用 account = Account.create! 之后,我有其他代码调用了 save! 回到模型上:account.foo = bar; account.save!。这显然再次调用 befor_save 并重新加密了我的字段. 我最终得到了这样的结果:

class Account < ActiveRecord::Base
  before_save :encrypt_username, if: :username_changed?
  before_save :encrypt_password, if: :password_changed?

  def encrypt_username
    crypt = ActiveSupport::MessageEncryptor.new(ENV['KEY'])
    self.username = crypt.encrypt_and_sign(username)
  end

  def encrypt_password
    crypt = ActiveSupport::MessageEncryptor.new(ENV['KEY'])
    self.password = crypt.encrypt_and_sign(password)
  end

  def decrypted_username
    crypt = ActiveSupport::MessageEncryptor.new(ENV['KEY'])
    crypt.decrypt_and_verify(username)
  end

  def decrypted_password
    crypt = ActiveSupport::MessageEncryptor.new(ENV['KEY'])
    crypt.decrypt_and_verify(password)
  end
end

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

Rails:为什么调用parent上的before_save?

来自分类Dev

Rails:为什么调用parent上的before_save?

来自分类Dev

API调用以在保存之前验证字段,这是在before_save还是在控制器内部完成?

来自分类Dev

具有嵌套属性创建的模型更改了before_validation和before_save之间的关联类型属性

来自分类Dev

Rails:`before_save`会干扰`save?`

来自分类Dev

通过多次调用函数创建表以返回记录

来自分类Dev

如何创建一个可以多次调用的bash文件?

来自分类Dev

创建 JSON 对象多次调用 Angular 2 RXJS

来自分类Dev

动态创建时多次调用事件处理程序

来自分类Dev

了解Ruby / Rails中的before_save

来自分类Dev

处理before_save导轨的智能方法

来自分类Dev

回形针,before_save和删除附件

来自分类Dev

before_save,去除字符串

来自分类Dev

Ruby on Rails:before_save字段小写

来自分类Dev

Smart way to handle before_save rails

来自分类Dev

验证后是否运行before_save?

来自分类Dev

在before_save中设置参数

来自分类Dev

模型before_save中的变量范围

来自分类Dev

Rails before_save无法正常工作

来自分类Dev

Before_save不运行滑轨4

来自分类Dev

多次调用Gradle buildConfig

来自分类Dev

多次调用setFrame?

来自分类Dev

阻止函数被多次调用

来自分类Dev

多次调用异步方法

来自分类Dev

多次调用邪恶的向导

来自分类Dev

递归多次调用

来自分类Dev

didAddAnnotationViews被多次调用

来自分类Dev

如何多次调用服务?

来自分类Dev

从UITabBarController多次调用NSNotification