Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Demonstrate counter_cache/destroy callback race condition
require 'rubygems'
require 'active_record'
ActiveRecord::Base.establish_connection("adapter" => "sqlite3", "database" => ":memory:")
class Widget < ActiveRecord::Base
connection.create_table table_name do |t|
t.string :name
t.integer :thing_count
end unless table_exists?
has_many :things
end
class Thing < ActiveRecord::Base
connection.create_table table_name do |t|
t.integer :widget_id
t.string :name
end unless table_exists?
belongs_to :widget, :counter_cache => :thing_count
end
widget = Widget.create!(:name => "test")
thing_1 = widget.things.create!(:name => "one")
thing_2 = widget.things.create!(:name => "two")
widget.reload
puts "widget has #{widget.things.size} things (#{widget.thing_count} in counter cache)"
t1 = Thing.find(thing_1.id)
t2 = Thing.find(thing_1.id)
puts "destroy thing #{t1.name}"
t1.destroy
widget.reload
puts "widget has #{widget.things.size} things (#{widget.thing_count} in counter cache)"
puts "destroy thing #{t1.name} (again)"
t2.destroy
widget.reload
puts "widget has #{widget.things.size} things (#{widget.thing_count} in counter cache)"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.