我发现 attr_encrypted 破坏了 Rails 的自动日期组合date_select
。我找到的最简单的解决方案是自己组装日期字符串并重写params
哈希。在您的控制器中:
protected
def compose_date(attributes, property)
# if the date is already composed, don't try to compose it
return unless attributes[property].nil?
keys, values = [], []
# find the keys representing the components of the date
attributes.each_key {|k| keys << k if k.start_with?(property) }
# assemble the date components in the right order and write to the params
keys.sort.each { |k| values << attributes[k]; attributes.delete(k); }
attributes[property] = values.join("-") unless values.empty?
end
然后你可以正常进行,一切都会好起来的:
def create
compose_date(params[:client], "dob")
@client = Client.new(params[:client])
...
end
编辑:起初我忘记了这一点,但我必须做一些额外的工作才能让日期正确存储在数据库中。attr_encrypted gem 总是想要存储字符串,所以如果您的数据不是字符串,那么您需要向它展示如何编组它。
我创建了一个模块来处理数据加密:
module ClientDataEncryption
def self.included(base)
base.class_eval do
attr_encrypted :ssn, :key => "my_ssn_key"
attr_encrypted :first_name, :last_name, :key => "my_name_key"
attr_encrypted :dob, :key => "my_dob_key",
:marshal => true, :marshaler => DateMarshaler
end
end
class DateMarshaler
def self.dump(date)
# if our "date" is already a string, don't try to convert it
date.is_a?(String) ? date : date.to_s(:db)
end
def self.load(date_string)
Date.parse(date_string)
end
end
end
然后将其包含在我的客户端模型中。