Skip to content

Instantly share code, notes, and snippets.

@njakobsen
Created November 18, 2011 01:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save njakobsen/1375294 to your computer and use it in GitHub Desktop.
Save njakobsen/1375294 to your computer and use it in GitHub Desktop.
Rails 3.1 poor handling of :dependent => :delete_all
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)
1000.times do
Post.create(:discussion => discussion)
end
# Reproduce the actual bug!
ActiveRecord::Base.logger = Logger.new(STDOUT)
Discussion.first.destroy
@njakobsen
Copy link
Author

Notice how Posts are loaded before cascading delete from discussion.destroy. Also notice how their IDs are included in the Post delete sql call.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment