0

我使用 before_create 回调函数在保存之前加密电子邮件字段。同样,现在我想在模型中解密它们,然后再将其用于显示。

为此应该使用什么?

我可以使用 afer_save 回调方法吗?

4

1 回答 1

2

此处描述了类似的情况:http: //api.rubyonrails.org/classes/ActiveRecord/Callbacks.html

class BankAccount < ActiveRecord::Base
   before_save      EncryptionWrapper.new
   after_save       EncryptionWrapper.new
   after_initialize EncryptionWrapper.new
end

class EncryptionWrapper
  def before_save(record)
    record.credit_card_number = encrypt(record.credit_card_number)
  end

  def after_save(record)
    record.credit_card_number = decrypt(record.credit_card_number)
  end

  alias_method :after_find, :after_save

  private
    def encrypt(value)
      # Secrecy is committed
    end

    def decrypt(value)
      # Secrecy is unveiled
    end
end
于 2012-07-10T05:30:55.200 回答