Skip to content

Instantly share code, notes, and snippets.

@njakobsen
Created May 12, 2012 19:20
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 njakobsen/2668335 to your computer and use it in GitHub Desktop.
Save njakobsen/2668335 to your computer and use it in GitHub Desktop.
model.association.delete_all performance issue
require 'active_record'
require 'logger'
# Print out what version we're running
puts "Active Record #{ActiveRecord::VERSION::STRING}"
# Connect to an in-memory sqlite3 database (more on this in a moment)
ActiveRecord::Base.establish_connection(:adapter => 'sqlite3', :database => ':memory:')
# Create the minimal database schema necessary to reproduce the bug
ActiveRecord::Schema.define do
create_table :discussions, :force => true do |t|
end
create_table :posts, :force => true do |t|
t.integer :discussion_id
end
end
# Create the minimal set of models to reproduce the bug
class Discussion < ActiveRecord::Base
has_many :posts, :dependent => :delete_all
end
class Post < ActiveRecord::Base
belongs_to :discussion
end
# Create some test data
#
# If you're demonstrating an exception, then this is probably not necessary,
# but if your bug is to do with the wrong data being returned from the database,
# then you'll probably need some test data to show that.
discussion = Discussion.create!
ActiveRecord::Base.logger = Logger.new(nil)
10000.times do
Post.create(:discussion => discussion)
end
# Reproduce the actual bug!
ActiveRecord::Base.logger = Logger.new(STDOUT)
Discussion.first.posts.delete_all
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment