Rails 7.1 - Handling Encryption of Sensitive Data with ActiveRecord Callbacks
I've been struggling with this for a few days now and could really use some help. I'm sure I'm missing something obvious here, but I've looked through the documentation and I'm still confused about I'm trying to implement encryption for sensitive user data in my Rails 7.1 application. I've set up the `attr_encrypted` gem to encrypt certain fields in my `User` model, but I'm running into issues with how to properly handle the encryption and decryption process during record creation and updates. Specifically, I want to ensure that the data is only encrypted before saving to the database and decrypted when retrieving it for display or processing. Here's a simplified version of my `User` model: ```ruby class User < ApplicationRecord attr_encrypted :ssn, key: 'a really secret key' attr_encrypted :credit_card_number, key: 'another secret key' before_save :encrypt_sensitive_data after_find :decrypt_sensitive_data private def encrypt_sensitive_data self.ssn = ssn if ssn_changed? self.credit_card_number = credit_card_number if credit_card_number_changed? end def decrypt_sensitive_data self.ssn = ssn self.credit_card_number = credit_card_number end end ``` When I create a new user, the data is being encrypted correctly, but when I try to update the userβs `credit_card_number`, I get the following behavior: ``` ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: "credit_card_number" ``` It seems that the encryption process is somehow interfering with the column access. I've also tried debugging by checking the column names returned by `User.column_names`, and it does show `credit_card_number`, but the behavior continues. What am I missing here? How can I ensure the fields are correctly encrypted and decrypted without running into database issues? This is part of a larger service I'm building. How would you solve this? I'm open to any suggestions. My team is using Ruby for this microservice.