Skip to content

Instantly share code, notes, and snippets.

@zerobearing2
Last active December 27, 2015 00:59
Show Gist options
  • Save zerobearing2/7242080 to your computer and use it in GitHub Desktop.
Save zerobearing2/7242080 to your computer and use it in GitHub Desktop.
ActiveRecord Store for Postgres' JSON data type
module ActiveRecord
module PgJsonStore
extend ActiveSupport::Concern
module ClassMethods
#
# Store (JSON) using Postgres
# JSON data type.
#
# Inspired by: http://api.rubyonrails.org/classes/ActiveRecord/Store.html
#
# Example:
#
# class User < ActiveRecord::Base
# include ActiveRecord::PgJsonStore
#
# pg_json_store :address, accessors: [:street1,
# :street2, :city, :state, :postal, :country]
# end
#
# User.new(city: "San Diego", state: "CA")
# => #<User address: {"city"=>"San Diego", "state"=>"CA"}>
#
def pg_json_store(column, options = {})
column = column.to_sym
accessors = options.delete(:accessors)
store_accessor(column, accessors) if accessors
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment