Skip to content

Instantly share code, notes, and snippets.

@bdurand
Created October 13, 2012 17:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bdurand/3885509 to your computer and use it in GitHub Desktop.
Save bdurand/3885509 to your computer and use it in GitHub Desktop.
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