使用build不会在has_many上创建连接模型:通过关联

时间:2012-08-09 23:09:40

标签: ruby-on-rails associations has-many-through

我的两个模特:

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

我无法使用player_to_team_histories创建@team_history.players.build,但它适用于@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 个答案:

答案 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

你的新玩家将被保存。

乔纳森·华莱士对this SO question的回答基本上是一样的。