Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to serialize ActiveRecord's JSON properties using HashWithIndifferentAccess?

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?

like image 571
thesmart Avatar asked Feb 23 '15 20:02

thesmart


1 Answers

| 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.

like image 72
Leonid Shevtsov Avatar answered Oct 04 '22 12:10

Leonid Shevtsov