Forum: Ruby on Rails Howto save / update using multiple tables?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Rath -. (Guest)
on 2006-03-10 01:24
# Controller
def create
  @person = Person.new(params[:person])
  @address = Address.new(params[:address])

  ...
end

If a person has an address, how can I save some data into 2 different
tables?

Can I do the following?

@person.address = @address
if @person.save
  render ...
else
  render_text "Error"
end

Or do I have to use:

if @person.save
  if @address.save
    render ...
  else
    render_text "Error"
else
  render_text "Error"
end
Rath -. (Guest)
on 2006-03-10 02:19
I found this example that it is supposed to be working

  def add_player
    case @request.method;
    when :get
      @team = Team.find(params[:id])
      @player = Player.new
    when :post
      @team = Team.find(params[:id])
      @player = Player.new(params[:player])
      @team.players << @player
      if @team.save
        flash[:notice] = 'Player was successfully added.'
        redirect_to :action => 'show', :id => params[:id]
      else
        render :action => 'add_player'
      end
    end
  end

Unfortunately the << is for arrays. Then I have tried something like:
@team.player = @player
if @team.save
  ...
else
  ...
end

Now the error is "Cannot add or update a child row: a foreign key
constraint fails"

What does that mean? Any ideas?
This topic is locked and can not be replied to.