title: Rails/ActiveRecord: has_one, belongs_to and before_create
body: <p>I'm having trouble figuring out how best to model my data. I have the following two models in my Rails application:</p>
  
  <pre><code>class Foo &lt; ActiveRecord::Base
    belongs_to :active_bar, :class_name =&gt; 'Bar'
    accepts_nested_attributes_for :active_bar
  
    before_create do |f|
      f.active_bar.foo = f
  
      # Causes stack overflow!
      f.active_bar.save!
    end
  end
  
  class Bar &lt; ActiveRecord::Base
    belongs_to :foo
  end
  
  test 'create with nested attributes' do
    f = Foo.create!(:name =&gt; 'foo-name', :active_bar_attributes =&gt; {:name =&gt; 'bar-name'})
    assert_equal 'foo-name', f.name
    assert_equal 'bar-name', f.active_bar.name
    assert_equal f, f.active_bar.foo
  
    f_id = f.to_param
  
    retrieved_f = Foo.find_by_id!(f_id)
    assert_equal retrieved_f, retrieved_f.active_bar.foo
  end
  </code></pre>
  
  <p>What you probably think is strange is the reflexive <code>belongs_to</code> relationship I'm attempting to model. My plan is that, eventually, <code>Foo</code> will have many instances of <code>Bar</code> while one instance will be considered "active". Thus I'm using <code>active_bar</code> to refer to this active instance. The problem with this code is that I need to set the <code>foo</code> property in <code>Bar</code> back to the parent <code>Foo</code> instance and I can't figure out the best place to do it (the <code>save!</code> call in <code>before_create</code> ends up being recursive and overflowing the stack) or even if this is the cleanest way to model this type of relationship.</p>
  
  <p>Essentially I'm attempting to model a user (equivalent to <code>Foo</code>) who has multiple e-mail addresses (equivalent to <code>Bar</code>) with one of the e-mail addresses marked as the user's primary address.</p>
  
  <p>Any advice?</p>