2012-08-09 59 views
1

我的2種型號:使用構建不創建連接模型上的has_many:通過關聯

Class TeamHistory < ActiveRecord::Base 
    has_many :player_to_team_histories 
    has_many :players, through: :player_to_team_histories 

    belongs_to :team 
end 

Class Player < ActiveRecord::Base 
    has_many :player_to_team_histories 
    has_many :team_histories, through: :player_to_team_histories 
end 

我不能去使用@team_history.players.build創建的player_to_team_histories,但它正常工作與@team_history.players.create

>>team = Team.create 
>>team_history = team.team_histories.create 
>>player = team_history.players.create 
>>player.team_histories.count 
1 
>>player2 = team_history.players.build 
>>player2.team_histories.count 
0 
>>player2.save 
>>player2.team_histories.count 
0 

回答

1

我做了一些挖掘,因爲我沒有立即知道答案。我發現#build確實設置了關聯模型,但僅從父模型到兒童。這意味着在你的例子中,rails的行爲如同設計。

>>team = Team.create 
>>team_history = team.team_histories.create 
>>player = team_history.players.create 
>>player.team_histories.count 
1 
>>player2 = team_history.players.build 
>>player2.team_histories.count 
0 

這完全如預期的那樣。如果你叫:

>>team_histories.players 

你的新玩家將在列表中。所以,如果不是的:

>>player2.save 

你跑:

>>team_histories.save 

新的球員將被保存。

Jonathan Wallace在this SO question上的回答說基本上是一樣的東西。

+0

複製粘貼錯誤。謝謝你的收穫。我剛剛從我的模型中複製不正確。同樣的問題仍然存在。 – 2012-08-09 23:34:49