Created
October 13, 2012 17:45
-
-
Save bdurand/3885509 to your computer and use it in GitHub Desktop.
Demonstrate counter_cache/destroy callback race condition
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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