我在我的应用程序中使用attr_encryptor gem。它在开发中没有任何障碍,但在生产中失败(Heroku)。我得到的错误是:
Mysql2::错误:字段'encrypted_ssn'没有默认值
这告诉我attr_encryptor甚至不尝试将加密值插入数据库。下面是我的模型代码:
class MerchantProfile < ActiveRecord::Base
after_initialize :init
belongs_to :user
validates_uniqueness_of :user
validates :phone, presence: true, format: /A[()0-9- +.]{10,20}z/
validates :date_of_birth, presence: true
validates :ssn, presence: true, format: /d{3}-?d{2}-?d{4}/
validates :account_number, presence: true
validates :routing_number, presence: true
before_validation :check_sensitive_fields
SENSITIVE_ATTRIBUTES = %i(ssn account_number routing_number)
SENSITIVE_ATTRIBUTES.each { |attr| attr_encryptor attr, key: Rails.configuration.database_field_encryption_key }
def init
self.date_of_birth ||= Time.zone.today
end
def check_sensitive_fields
return unless persisted?
SENSITIVE_ATTRIBUTES.each do |attr|
if object_value_matches_database_value?(attr)
assign_attributes(attr => value_from_database(attr))
end
end
end
def object_value_matches_database_value?(attr)
if new_record?
raise "#{self.class.name} must be saved before #{attr} values can be checked."
end
masked(attr) == SensitiveValue.new(value_from_database(attr)).mask
end
def value_from_database(attr)
self.class.find(id).send(attr)
end
def masked(attr)
SensitiveValue.new(send(attr) || "").mask
end
def should_mask?(attr)
persisted? and object_value_matches_database_value?(attr)
end
def masked_if_appropriate(attr)
should_mask?(attr) ? masked(attr) : send(attr)
end
end
显然gem正在加载,因为我正在做的attr_encryptor
调用工作得很好。由于某些原因,gem无法正常工作。
你知道会发生什么吗?
我重启了Heroku,现在它可以工作了。我以为Heroku会在你部署的时候自动重启。