2012-08-09 61 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