title: How do I define synthetic attributes for an ActiveRecord model?
body: <p>I have an ActiveRecord model whose fields <em>mostly</em> come from the database.  There are additional attributes, which come from a nested serialised blob of stuff.  This has been done so that I can use these attributes from forms without having to jump through hoops (or so I thought in the beginning, anyway) while allowing forwards and backwards compatibility without having to write complicated migrations.</p>
  
  <p>Basically I am doing this:</p>
  
  <pre><code>class Licence &lt; ActiveRecord::Base
    attr_accessor :load_worker_count
    strip_attributes!
  
    validates_numericality_of :load_worker_count,
      :greater_than =&gt; 2, :allow_nil =&gt; true, :allow_blank =&gt; true
  
    before_save :serialise_fields_into_properties
  
    def serialise_fields_into_properties
      ...
    end
  
    def after_initialize
      ...
    end
  
    ...
  end
  </code></pre>
  
  <p>The problem I noticed was that I can't get empty values in <code>:load_worker_count</code> to be accepted by the validator, because:</p>
  
  <ul>
  <li>If I omit <code>:allow_blank</code>, it fails validation complaining about it being blank</li>
  <li>If I put in <code>:allow_blank</code>, it converts the blank to 0, which when fails on the <code>:greater_than =&gt; 2</code></li>
  </ul>
  
  <p>In tracking down why these blank values are getting to the validation stage in the first place, I discovered the root of the problem: <strong><code>strip_attributes!</code> only affects actual attributes, as returned by the <code>attributes</code> method.</strong>  So the values which should be nil at time of validation are not.  So it feels like the root cause is that the synthetic attributes I added in aren't seen when setting which attributes to strip, so therefore I ask:</p>
  
  <p>Is there a proper way of creating synthetic attributes which are recognised as proper attributes by other code which integrates with ActiveRecord?</p>