title: How do I validate an attr based on whether a checkbox is checked in Rails?
body: <p>I want to validate the presence of a <code>shipping_address</code> unless it's the same as the billing address. I wrote a <code>attr_writer</code> for it. I want to initialise with object with this attr checked.</p>
  
  <pre><code>class Order &lt; ActiveRecord::Base
    attr_writer :ship_to_billing_address
    accepts_nested_attributes_for :billing_address, :shipping_address
  
    validates :shipping_address, presence: true, unless: -&gt; { self.ship_to_billing_address? }
  
    def ship_to_billing_address
      @ship_to_billing_address = true if @ship_to_billing_address.nil?
      @ship_to_billing_address
    end
  
    def ship_to_billing_address?
      ship_to_billing_address
    end
  end
  </code></pre>
  
  <p>Here's the form:</p>
  
  <pre><code># Use my shipping address as billing address.
  = f.check_box :ship_to_billing_address
  </code></pre>
  
  <p>This doesn't work, however. The form submits 0 and 1 for the values. So I changed the method to this:</p>
  
  <pre><code>  def ship_to_billing_address?
      ship_to_billing_address == 1 ? true: false
    end
  </code></pre>
  
  <p>Then to this just to see if validations still kick in, and they still do...</p>
  
  <pre><code>  def ship_to_billing_address?
      true
    end
  </code></pre>
  
  <p>But the validations are still kicking in even when it returns false.</p>
  
  <p>After three hours I out of ways for fixing this...</p>