次のモデルがあるとします。
class Location < Active::Record
has_many :storables, foreign_key: :bin_id
# ...
end
class Storable < Active::Record
belongs_to :bin, class_name: :Location, counter_cache: true
# ...
end
次の仕様を実行すると、counter_cache
が正しくインクリメントされません。メソッド#1
と#2
動作は期待どおりですが、そうではありません#3
。何を与える?
describe "location storables" do
specify "adding a storable increments the counter cache" do
l = Location.create
l.storables_count.should == 0 #=> PASSES
# method 1
s = Storable.create(bin: l)
l.reload
l.storables_count.should == 1 #=> PASSES
# method 2
l.storables.create
l.reload
l.storables_count.should == 2 #=> PASSES
# method 3
l.storables << Storable.create
l.reload
l.storables_count.should == 3 #=> FAILS, got 2 not 3
end
end
私はcounter_cache の半分が機能していることに本当に混乱しています。構成の問題も見つかりません。
このプロジェクトではRails 3.2.12を使用します。
アップデート
Rails 4へのアップグレードは役に立ちませんでした。また、方法 3 を次のように変更すると、テストに合格します。
# method 3
l.storables << Storable.create
puts "proxy : #{l.storables.count}" #=> 3
puts "relation : #{Storable.count}" #=> 3
puts "cache : #{l.storables_count}" #=> 2
Location.reset_counters(l.id, :storables) # corrects cache
l.reload
l.storables_count.should == 3 #=> PASSES
これが自動的に行われないのはなぜですか?