我發現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
然後在我的客戶端模型包括它。
對不起,我花了這麼久回覆,但非常感謝你!它完美的作品。我一直試圖弄清楚這個問題將近一週。我唯一需要做的事情是在編輯客戶端時,日期將字符串解析回日期,就是這樣。再次感謝。 – WillieG