Miguel Morujão
Miguel Morujão

Reputation: 1161

Creating a new object when creating another

I have 3 models: account, player_team and team. Player team serves to associate accounts and teams. Player_team table has account_id and team_id attributes. When I create the team, i should at least have the account who created it belonging to the team. What am i doing wrong ?Any help would be appreciated, Thanks.

        def create
        @team = Team.new(team_params)
        @team.save
        @team_player = current_account.player_teams.build(:account_id => current_account.id, :team_id => @team.id)
        @team_player.save
        respond_with(@team)
      end

class Account < ActiveRecord::Base
  has_many :player_teams
  has_many :teams, through: :player_teams

class Team < ActiveRecord::Base
  has_many :player_teams
  has_many :accounts, through: :player_teams
end

class PlayerTeam < ActiveRecord::Base
  belongs_to :account
  belongs_to :team
end

Upvotes: 0

Views: 36

Answers (3)

Hristo Georgiev
Hristo Georgiev

Reputation: 2519

Because you are creating the object right into the controller (instead of just declaring it and opening a form in the view to enter parameters) , you have to use the

new

keyword.

A solution of your problem would be

@team_player = current_account.player_teams.new(:account_id => current_account.id, :team_id => @team.id)

Upvotes: 1

Jiř&#237; Posp&#237;šil
Jiř&#237; Posp&#237;šil

Reputation: 14402

Note that there's no need to go through all this trouble manually. You could have just said:

respond_with(@team = current_account.teams.create(team_params))

Upvotes: 1

RichardAE
RichardAE

Reputation: 2970

This should work:

def create
  @team = Team.new(team_params)
  @team.save
  @team_player = current_account.build_player_team(:account_id => current_account.id, :team_id => @team.id)
  @team_player.save
  respond_with(@team)
end

Build on it's own won't save, and saving the parent won't do anything. You need to use build_player_team, or use create() instead of build. Either would work.

def create
  @team = Team.new(team_params)
  @team.save
  @team_player = current_account.player_teams.create(:account_id => current_account.id, :team_id => @team.id)
  @team_player.save
  respond_with(@team)
end

Upvotes: 1

Related Questions