it's already there:

class Team < ActiveRecord::Base
  has_many :players
  #
  # ...
end

team = Team.find(4711)
player = team.players.create



-------- Original-Nachricht --------
Datum: Wed, 19 Jul 2006 19:06:16 +0900
Von: Phillip Hutchings <sitharus / sitharus.com>
An: ruby-talk / ruby-lang.org
Betreff: Re: Rails: Saving an object into DB

> On 7/19/06, Kev Jackson <foamdino / gmail.com> wrote:
> > >
> > > And my Player model is:
> > >
> > > class Player < ActiveRecord::Base
> > >   belongs_to :team
> > >
> > >   # Crea un jugador con los valores por defecto
> > >   def Player.create_player(team_id)
> > >     player = Player.new
> > >     player.relate_to_team(team_id)
> > >     player.save <-------------------------------- LINE 15
> > >
> >
> > try @player.save
> 
> Why do you think that would work? @player isn't defined.
> 
> And for the original question. I have no idea if this will work, but
> >from my experience with ActiveRecord it might help.
> 
> Firstly, what's with relate_to_team? Just use team_id =, ActiveRecord
> does tricky things in the background, so always use the accessors.
> 
> Secondly, just so you know, you don't need the return on the last line
> - the result of the last evaluated expression is always returned, so
> for example:
> def two_plus_one
>   2+1
> end
> 
> x = two_plus_one
> => x = 3
> 
> class Player < ActiveRecord::Base
>   belongs_to :team
> 
>   def Player.create_player(team_id)
>     player = Player.new
>     player.team_id = team_id
>     player.save
>     player # The last evaluated line in a Ruby method is automatically
> returned
>   end
> end
> 
> -- 
> Phillip Hutchings
> http://www.sitharus.com/