Is there a way to serialize ActiveRecord's JSON properties using HashWithIndifferentAccess?
| 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.
If your root object is an array you need to handle it slightly differently.
Rails 5+
class User < ActiveRecord::Base
serialize :preferences, HashSerializer
serialize :some_list, ArrayHashSerializer
end
class HashSerializer
def self.dump(hash)
hash
end
def self.load(hash)
(hash || {}).with_indifferent_access
end
end
class ArrayHashSerializer
def self.dump(array)
array
end
def self.load(array)
(array || []).map(&:with_indifferent_access)
end
end
Rails <= 4
class User < ActiveRecord::Base
serialize :preferences, HashSerializer
serialize :some_list, ArrayHashSerializer
end
class HashSerializer
def self.dump(hash)
hash.to_json
end
def self.load(hash)
(hash || {}).with_indifferent_access
end
end
class ArrayHashSerializer
def self.dump(array)
array.to_json
end
def self.load(array)
(array || []).map(&:with_indifferent_access)
end
end