Created
December 25, 2019 08:32
-
-
Save dpaluy/ca72531037aaa36e052c2d9f24fd6267 to your computer and use it in GitHub Desktop.
store large JSON in PostgreSQL with Rails Attributes API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # app/types/binary_hash.rb | |
| class BinaryHash < ActiveRecord::Type::Binary | |
| def serialize(value) | |
| super value_to_binary(value.to_json) | |
| end | |
| def deserialize(value) | |
| super case value | |
| when NilClass | |
| {} | |
| when ActiveModel::Type::Binary::Data | |
| value_to_hash(value.to_s) | |
| else | |
| value_to_hash(PG::Connection.unescape_bytea(value)) | |
| end | |
| end | |
| private | |
| def value_to_hash(value) | |
| JSON.parse( | |
| ActiveSupport::Gzip.decompress(value), | |
| symbolize_names: true | |
| ) || {} | |
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| add_column :reports, :data, :binary |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # app/models/report.rb | |
| class Report < ApplicationRecord | |
| attribute :data, :binary_hash | |
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # config/initializers/types.rb | |
| ActiveRecord::Type.register(:binary_hash, BinaryHash) |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
reference: https://dev.to/jetrockets/how-to-store-large-json-in-postgresql-with-rails-attributes-api-52co