2017-06-05 16 views
0

我有以下關係:滑軌:destroy_all和更新的has_many大小

class Match 
    has_many :players 
end 

在一個示例情況下,我有2個玩家,一個與屬性團隊= 1和其它隊比賽= 2

在我打電話給match.players.where(team: 1).destroy_all之後,有一些代碼在使用match.players.size 之後執行。但是,尺寸現在爲3,而不是尺寸爲2。如何更新尺寸屬性?我不能叫match.reload因爲有這個執行過程中對該對象所做的

回答

1

您可以考慮使用counter_cache這等變化,所以你的播放器的模型得到:

class Player < ApplicationRecord 
    belongs_to :match, dependent: :destroy, counter_cache: true 
end 

你必須生成一個遷移和:

add_column :matches, :player_count, :integer 

當增加一個球員這樣/從比賽櫃檯緩存列會自動更新刪除。

更多的信息在這裏http://guides.rubyonrails.org/association_basics.html#options-for-belongs-to-counter-cache