我正在尝试使用ActiveModel :: Type :: Binary库将base64编码数据gzip存储在postgres中。
create_table :documents do
t.binary :document_data
end
我的模特:
class Document < ApplicationRecord
class DocumentData < ActiveModel::Type::Binary
def serialize(value)
super compress(value)
end
def deserialize(value)
super decompress(value)
end
private
def compress(value)
ActiveSupport::Gzip.compress(Base64.decode64(value))
end
def decompress(value)
Base64.strict_encode64(ActiveSupport::Gzip.decompress(value))
end
end
attribute :document_data, DocumentData.new
end
serialize
方法似乎按预期工作,但是当调用deserialize
时,value
的编码方式不同,Gzip.decompress
失败。
感谢您的帮助。
修改:
如果记录为PG::Connection.unescape_bytea
,我在ActiveRecord::ConnectionAdapters::PostgreSQL::OID::Bytea#deserialize
中找不到Type::Binary::Data
。我在PG::Connection.unescape_bytea
之前打电话给decompress
并且它有效,但我对这个解决方案不满意,所以我现在暂不开放。