Workaround for corruption in saving bytea data thru rails

I’m not sure where the bug is, but when saving some binary data that was generated in a Rails3 before_create callback, it kept getting truncated in the actual INSERT INTO statement (though it appeared fine even in after_save callback, it was truncated in the database). Using PostgreSQL 8.4.7 with pg (0.9.0) and activerecord 3.0.5

Seemed like it could be related to this fixed bug, but my problem is on the save itself:
https://rails.lighthouseapp.com/projects/8994/tickets/611-cannot-write-certain-binary-data-to-postgresql-bytea-columns-in-2-1-0

In any case, found a simple workaround: uuencode the data first, and uudecode on loading.

   before_create do
      ... stuff that builds my_hash ...
      self.my_hash = Base64.encode64(Marshal.dump(my_hash))
   end

Then later, to reconstitute the hash,

   loaded_hash = Marshal.load(Base64.decode64(@record.my_hash))

Leave a Reply