Reputation: 641
I am trying to figure out how to change an attribute before attr_encrypted does its encrypting.
I want to remove dashes from a number before I save it to a database encrypted.
attr_encrypted :ssn, key: Rails.application.secrets.secret_encrypt_key
validates :ssn, format: { with: /\d{3}-\d{2}-\d{4}/,
message: "SSN must be separated by dashes" },
allow_nil: true
validates :ssn, length: { is: 11 }, allow_nil: true
before_save :format_ssn
def format_ssn
return if ssn.nil?
ssn.delete!("-")
end
This is what I currently have. It does not work in the rails console. I can't for the life of me think of how else to accomplish this. I was trying to use a setter originally but attr_encrypted would no longer do its magic if I did that. I'm assuming that is because attr_encrypted itself is reusing the setter.
Any suggestions on how to format before attr_encrypted encrypts would be greatly appreciated.
Upvotes: 1
Views: 324
Reputation: 641
Ok I figured it out.
Doing:
def format_ssn
return if ssn.nil?
self.ssn = ssn.delete!("-")
end
solves the issue
Upvotes: 1