Q:

How to set a default value for a JSON column/attribute in a Rails active record?

I have something like this class
#  json_column  :json
class MyClass < ActiveRecord::Base
  def name=(val)
    json_column[:name] = val
  end

  def name
    json_column[:name]
  end
end

It works fine when I load data, but if I create a new instance like MyClass.new(name: "foo") my problems begins...
If I let it as it is, it will trhow an exception in the name= because nil is not a hash :).
If I try to initialize the json_column in the after_initialize method
after_initialize { self.json_column ||= {}  }

It also don't work because it seems that the after_initialize is called after set the parameters
Does someone have some hint how should I fix this problem?
Thank you in advance

A:

You can use store then after_initialize callbacks like this to assign default values

    store :json_column_name, accessors: [:key_name], coder: Hash # in mysql

    store_accessor :json_column_name, [:key_name] # in psql

    after_initialize :initialize_defaults, :if => :new_record?

    def initialize_defaults
        self.key_name = value
    end

