title: Rails optional belongs_to
body: <p>I'm writing a Rails frontend for inventory management. I want users to be able to register products, so I have:</p>
  
  <pre><code>class User &lt; ActiveRecord::Base
    has_many :products
    # &lt;snip&gt;
  end
  </code></pre>
  
  <p>and</p>
  
  <pre><code>class Product &lt; ActiveRecord::Base
    belongs_to :user
    # &lt;snip&gt;
  end
  </code></pre>
  
  <p>The problem is that products are created prior to being registered by a user. That is, it's perfectly acceptable to call <code>Product.create</code> and just have it set the <code>user_id</code> to <code>nil</code>. As you can imagine, though, Rails doesn't support this out of the box:</p>
  
  <pre><code>&gt; Product.create!
     (0.3ms)  SELECT COUNT(*) FROM "products" WHERE "products"."type" IN ('Product')
     (0.1ms)  begin transaction
     (0.1ms)  rollback transaction
  ActiveRecord::RecordInvalid: Validation failed: User can't be blank
      from ~/.rvm/gems/ruby-2.0.0-p0/gems/activerecord-3.2.13/lib/active_record/validations.rb:56:in `save!'
  </code></pre>
  
  <p>I've thought about a bunch of kludgey workarounds, the most appealing of which is to have a <code>NullUser</code> subclassing <code>User</code> and use that to create products. But that still seems like a hack. What's the Rails Way with this?</p>
  
  <p>Thanks.</p>
  
  <hr>
  
  <p>The relevant migration:</p>
  
  <pre><code>class AddUseridToProducts &lt; ActiveRecord::Migration
    def change
      add_column :products, :user_id, :integer
    end
  end
  </code></pre>
  
  <p>and later:</p>
  
  <pre><code>class Changeuseridtobeoptionalforproducts &lt; ActiveRecord::Migration
    def change
      change_column :products, :user_id, :integer, null: true
    end
  end
  </code></pre>