title: Creating many related models before_save
body: <p>I have a User model with devise, a Team model, a Player model and a Trainer model. I want that when the User signs up, its associated team is created along with the associated trainer and players. I have set up the models as below:</p>
  
  <p>user.rb</p>
  
  <pre><code>has_one :team
  has_one :trainer, :through =&gt; :team
  has_many :players, :through =&gt; :team
  accepts_nested_attributes_for :team, :allow_destroy =&gt; true
  
  before_save :create_team
  
  def create_team
    @team = Team.new(params[:team])
    @team.user = self
    @team.save
  end
  </code></pre>
  
  <p>team.rb</p>
  
  <pre><code>belongs_to :user
  has_one :trainer
  has_many :players
  accepts_nested_attributes_for :trainer, :allow_destroy =&gt; true
  accepts_nested_attributes_for :player, :allow_destroy =&gt; true
  </code></pre>
  
  <p>trainer.rb and player.rb</p>
  
  <pre><code>belongs_to :team
  </code></pre>
  
  <p>I have not added the create_trainer and create_player functions, since I want the user to select them later in the game. So they should be empty during the creation of the user.</p>
  
  <p>But the sign up process gives the following error:</p>
  
  <pre><code>No association found for name `trainer'. Has it been defined yet?
  </code></pre>
  
  <p>and refers to the line:</p>
  
  <pre><code>accepts_nested_attributes_for :trainer, :allow_destroy =&gt; true
  </code></pre>
  
  <p>in team.rb. What is wrong with having the Trainer item not defined yet, if there is no validation of presence of Trainer defined in the Team model? I tried adding some lines to the Trainer model, to set the attributes to default values like:</p>
  
  <pre><code>morale.default =&gt; (5..12).to_a.sample
  </code></pre>
  
  <p>but it gave further errors, so is probably wrong. Any comment is greatly appreciated, especially anything criticising the basis of tinking here, since I am a noob.</p>