Home > Software engineering >  Rails - Summing an encrypted field
Rails - Summing an encrypted field

Time:10-13

I have an encrypted column :amount following using Lockbox that I need to sum in my controller.

Currently, I have -

transaction_controller.rb 

@one_month_transactions_sum = transactions.where(transaction_date: 1.month.ago..Date.today).sum(:amount).abs()

This is giving me the error - PG::UndefinedColumn: ERROR: column "amount" does not exist LINE 1: SELECT SUM(amount) FROM "transactions" WHERE "transactions".... which makes sense because I am asking rails to use the PG SUM function on a column I changed to be a ciphertext.

How would I sum the transactions at the controller level with an encrypted column?

CodePudding user response:

If you send data to database as opaque binary blobs, you (naturally) lose ability to manipulate those fields directly in the database. It appears that your only option is to fetch encrypted values into the app, decrypt and sum in ruby (slowly). I haven't tried this specific library, but I'd guess that something like this should work:

transactions.where(...).map(&:amount).sum
  • Related