1

我的 2 个模型:

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
4

1 回答 1

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

您的新玩家将被保存。

乔纳森华莱士对这个 SO 问题的回答基本上是一样的。

于 2012-08-09T23:26:11.650 回答