2014-11-17 3 views
0

계정, player_team 및 팀이라는 세 가지 모델이 있습니다. 플레이어 팀은 계정과 팀을 연결하는 역할을합니다. Player_team 테이블에는 account_id 및 team_id 특성이 있습니다. 팀을 만들 때 팀에 속한 계정을 만들었어야합니다. 내가 뭘 잘못 했니? 어떤 도움을 주셔서 감사하겠습니다. 고마워요. 그 자체에다른 개체를 만들 때 새 개체 만들기

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 

빌드는 저장되지 않으며, 부모를 저장하면 아무것도하지 않습니다 :

 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 
+1

것입니까? 'PlayerTeam'을 만들지 못했습니까? –

+0

'build'대신 'new'를 넣으려고 했습니까? –

+0

@HristoGeorgiev – MMrj

답변

1

, 당신은

new 
을 사용해야합니다

키워드.

문제의 해결책은 점점 어떤 오류

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

이 작동합니다. build_player_team을 사용하거나 build 대신 create()를 사용해야합니다. 어느 쪽이든 작동합니다.

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

이 모든 문제를 수동으로 처리 할 필요가 없습니다. 당신은 방금 말한 수 :

당신은 (그것을 선언하고 매개 변수를 입력합니다보기에서 폼을 여는 단지 대신에) 바로 컨트롤러로 객체를 생성하기 때문에
respond_with(@team = current_account.teams.create(team_params)) 
관련 문제