I made a patch which temporally fixes a bug introduced in Rails 2.1 described at #611 cannot write certain binary data to postgresql bytea columns in 2.1.0.

The symptom of the bug is sometimes corrupted binary data when saved to or accessed from BYTEA column on PostgreSQL. The problem is caused by conversion procedure in ActiveRecord’s Postgres Adapter, which checks if data coming from database is escaped or not. It determines escaped string by regex /\\\d{3}/ which matches octal sequences like ”\234”. However if there is a binary non escaped data which coincidentally has got such sequence then unescaping routine will corrupt the data.

Below is the monkey patch file for Rails 2.1.0 which I made from diff patches provided on the bug tracker page. It should be put into /config/initializers/ of your Rails application.


The file may not be compatible with future versions of framework especially when the bug #611 will be fixed, therefore check its status every time you do Rails upgrade.