title: Creating nested models - Rails 3.1
body: <p>I am trying to create 3 nested models at once, and have trouble with my validations.  </p>
  
  <p>These are my models:</p>
  
  <pre><code>class UserEntity &lt; ActiveRecord::Base
    has_many    :users,           :dependent =&gt; :restrict, :autosave =&gt; true
  end
  
  class User &lt; ActiveRecord::Base
    has_many    :user_login_services, :dependent =&gt; :destroy, :autosave =&gt; true
    belongs_to  :user_entity
  end
  
  class UserLoginService &lt; ActiveRecord::Base
    belongs_to :user
    #validates :user_id, :presence =&gt; true
  end
  </code></pre>
  
  <p>(UserEntity can be a company, with many users.  UserLoginService is used for Omniauth services such as Facebook, openID, etc.)</p>
  
  <p>Users are created with</p>
  
  <pre><code>def new_user_login(tokens)
    user_entity = UserEntity.new
    user = user_entity.users.build(:email =&gt; tokens[:email], :password =&gt; Devise.friendly_token[0,20], :first_name =&gt; tokens[:first_name], :last_name =&gt; tokens[:last_name], :has_local_password =&gt; false)
    user.skip_confirmation!
    user.user_login_services.build(:provider =&gt; tokens[:provider], :uid =&gt; tokens[:uid], :uname =&gt; tokens[:name], :uemail =&gt; tokens[:email])     
    user_entity.save! 
    user.confirm!
  </code></pre>
  
  <p>This code seems to be working fine, and creates appropriate entries in all 3 tables.  The problem occurs when I uncomment 'validates :user_id, :presence => true' in UserLoginService, which gets me</p>
  
  <pre><code>ActiveRecord::RecordInvalid (Validation failed: Users user login services user can't be blank):
    app/controllers/users/omniauth_callbacks_controller.rb:86:in `new_user_login'
  </code></pre>
  
  <p>Note that the code seems to be working fine without the validation, and user_id in the user_login_services table is set to the proper value.</p>
  
  <p>Why am I getting this error, and how do I solve this?</p>