title: How to set a default value for a JSON column/attribute in a Rails active record?
body: <p>I have something like this class</p>
  
  <pre class="lang-rb prettyprint-override"><code>#  json_column  :json
  class MyClass &lt; ActiveRecord::Base
    def name=(val)
      json_column[:name] = val
    end
  
    def name
      json_column[:name]
    end
  end
  </code></pre>
  
  <p>It works fine when I load data, but if I create a new instance like <code>MyClass.new(name: "foo")</code> my problems begins...</p>
  
  <p>If I let it as it is, it will trhow an exception in the <code>name=</code> because nil is not a hash :).</p>
  
  <p>If I try to initialize the json_column in the after_initialize method</p>
  
  <pre class="lang-rb prettyprint-override"><code>after_initialize { self.json_column ||= {}  }
  </code></pre>
  
  <p>It also don't work because it seems that the <code>after_initialize</code> is called after set the parameters</p>
  
  <p>Does someone have some hint how should I fix this problem?
  Thank you in advance</p>