我有以下关系:
class Match
has_many :players
end
在一个示例中,我与2名球员匹配,其中一名队员属性为队伍= 1而另一队队员= 2
我致电match.players.where(team: 1).destroy_all
后,会在下方执行使用match.players.size
的代码
但是,而不是大小为2,现在的大小是3.如何更新大小属性?我无法调用match.reload
,因为在执行期间对此对象进行了其他更改
答案 0 :(得分: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