Created
February 7, 2018 00:07
-
-
Save noma4i/3034ac3776cdfea2730f2ca81dd3f836 to your computer and use it in GitHub Desktop.
Rails 5.1.5 AR uses 3 queries to destroy 2 records
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
# frozen_string_literal: true | |
begin | |
require 'bundler/inline' | |
rescue LoadError => e | |
warn 'Bundler version 1.10 or later is required. Please update your Bundler' | |
raise e | |
end | |
gemfile(true) do | |
source 'https://rubygems.org' | |
git_source(:github) { |repo| "https://github.com/#{repo}.git" } | |
# gem 'rails', github: 'rails/rails' | |
gem 'rails', '5.1.5rc1' | |
gem 'sqlite3' | |
end | |
require 'active_record' | |
require 'minitest/autorun' | |
require 'logger' | |
# This connection will do for database-independent bug reports. | |
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:') | |
ActiveRecord::Base.logger = Logger.new(STDOUT) | |
ActiveRecord::Schema.define do | |
create_table :parent_nodes, force: true do |t| | |
end | |
create_table :child_nodes, force: true do |t| | |
t.integer :ancestor_id | |
t.string :ancestor_type | |
end | |
end | |
class ParentNode < ActiveRecord::Base | |
has_one :child_node, as: :ancestor, dependent: :destroy | |
accepts_nested_attributes_for :child_node | |
end | |
class ChildNode < ActiveRecord::Base | |
belongs_to :ancestor, polymorphic: true, touch: true, optional: true | |
end | |
class BugTest < Minitest::Test | |
def test_association_stuff | |
parent_node = ParentNode.create! | |
parent_node.build_child_node.save! | |
c = count_queries do | |
ParentNode.first.destroy | |
end | |
assert_equal 6, c | |
end | |
private | |
def count_queries(&block) | |
count = 0 | |
counter_f = lambda { |_name, _started, _finished, _unique_id, payload| | |
count += 1 unless payload[:name].in? %w[CACHE SCHEMA] | |
} | |
ActiveSupport::Notifications.subscribed(counter_f, 'sql.active_record', &block) | |
count | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment