2012-08-09 64 views
2

當我試圖通過has_many:through關係添加對象時,我收到了奇怪的行爲。Rails追加不添加對象has_many:通過

我的模型:

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沒有新創建TeamHistory添加到team_histories陣列?

我正在使用Ruby 1.9.2。

更新

發佈一個問題Github上: https://github.com/rails/rails/issues/7364

+0

不錯的問題。我認爲這是微不足道的,但我找不到任何附加方法的文檔... – davidrac 2012-08-09 19:04:41

回答

1

據我所知,append不是一個ActiveRecord的方法,而是通過傳遞到底層(臨時)數組,表示team_histories。這種方法可用但可能是錯誤或疏忽,但無法正確保存關聯,但與此同時,您應該僅使用push<<來實現此目的。

+0

這是正確的。 – deefour 2012-08-09 19:32:23