Is there a way to serialize ActiveRecord's JSON properties using HashWithIndifferentAccess?
activerecord, json, ruby, ruby-on-rails
Solution
| You can use a custom serializer so you can access the JSON object with symbols as well.
# app/models/user.rb
class User < ActiveRecord::Base
serialize :preferences, HashSerializer
end
# app/serializers/hash_serializer.rb
class HashSerializer
def self.dump(hash)
hash
end
def self.load(hash)
(hash || {}).with_indifferent_access
end
end
Full credit - sans googling - goes to http://nandovieira.com/using-postgresql-and-jsonb-with-ruby-on-rails.
Problem
I am using `ActiveRecord::ConnectionAdapters::PostgreSQLAdapter` in a Rails application. Suppose I have a schema: ``` create_table "foo", id: :bigserial, force: :cascade do |t| t.string "name" t.jsonb "data", null: false end ``` Now suppose I run the following code: ``` class Foo < ActiveRecord::Base self.table_name = :foo end my_foo = Foo.create!(:name => 'foobar', :data => {:a => 'hello'}) my_foo = Foo.where(:name => 'foobar').first! puts my_foo.data[:a] puts my_foo.data['a'] ``` The output would be: ``` # nil # 'hello' ``` Is it possible to ask ActiveRecord to automatically deserialize jsonb types using HashWithIndifferentAccess?