创建另一个时创建新对象

时间:2014-11-17 14:27:03

标签: ruby-on-rails

我有3个模型:account,player_team和team。球员团队用于关联账户和团队。 Player_team表具有account_id和team_id属性。当我创建团队时,我至少应该创建属于团队的帐户。我做错了什么?任何帮助将不胜感激,谢谢。

        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

3 个答案:

答案 0 :(得分:1)

这应该有效:

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_player_team,或使用create()而不是build。要么工作。

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

答案 1 :(得分:1)

请注意,无需手动完成所有这些麻烦。你可以说:

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

答案 2 :(得分:1)

因为您正在将对象创建到控制器中(而不是仅仅声明它并在视图中打开表单以输入参数),您必须使用

new

关键字。

您的问题的解决方案是

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