2

尝试通过 has_many :through 关系添加对象时,我遇到了奇怪的行为。

我的模型:

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

编码:

>>p = Player.first
>>p.team_histories.count
0
>>p.team_histories.append TeamHistory.create
>>p.team_histories.count
0
>>p.team_histories.push TeamHistory.create
>>p.team_histories.count
1
>>p.team_histories << TeamHistory.create
>>p.team_histories.count
2

为什么不append将新创建的添加TeamHistoryteam_histories数组中?

我正在使用 Ruby 1.9.2。

更新

向 Github 发布问题: https ://github.com/rails/rails/issues/7364

4

1 回答 1

1

据我所知,append不是 ActiveRecord 方法,而是传递给表示team_histories. 此方法可用但无法正确保存关联可能是错误或疏忽,但同时您应该只使用push<<用于此目的。

于 2012-08-09T19:31:12.093 回答