Search code examples
ruby-on-railsformsruby-on-rails-4attr-encrypted

Redacting a SSN on form display under Rails 4?


I have a Rails 4 application and I am using the attr_encrypted gem to store SSN in an encrypted form in the DB.

What I am trying to do is only display the last 4 digits when editing / showing the form. So essentially once the SSN has been saved, users can't see the full SSN in the form. So I've tried doing the following,

class PaymentData < ActiveRecord::Base
  attr_encrypted :ssn, key: 'secret'

  alias_method :org_ssn, :ssn
  def ssn
    org_ssn.reverse # just a way of testing if this works
  end
end

What I am seeing that the on the show form, which uses <%= @payment_data.ssn %>, it works fine. But on my edit form which is using <%= f.input :ssn %>, the edit field is prepopulated with the full SSN.

Note: I am using the simple_form gem for my forms, but if I use the basic, <%= f.text_field :ssn %> syntax, I see the same full SSN.

What am I doing wrong here?


Solution

  • This is what I ended up doing,

    def obfuscated_ssn
      return ssn unless ssn && ssn.size > 3
      ssn.last(4).rjust(ssn.length, '*')
    end
    
    def obfuscated_ssn=(ssn)
      self.ssn = ssn unless ssn.include?('*')
    end
    

    This is a bit hacky, but it displays the SSN with a redacted string, but then doesn't save a string with the redacted bits, *, to keep bad data from getting the database.