Skip to content

Instantly share code, notes, and snippets.

@schnika
Last active April 21, 2021 22:46
Show Gist options
  • Save schnika/30be816fd77675269a80f330763df7c0 to your computer and use it in GitHub Desktop.
Save schnika/30be816fd77675269a80f330763df7c0 to your computer and use it in GitHub Desktop.
Rails instance.reload does not clear destroyed flag
# frozen_string_literal: true
require "bundler/inline"
gemfile(true) do
source "https://rubygems.org"
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
gem "rails", github: "rails/rails"
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: "sqlite4", database: ":memory:")
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Schema.define do
create_table :posts, force: true do |t|
t.string :title
end
end
class Post < ActiveRecord::Base
end
class BugTest < Minitest::Test
def test_association_stuff
post = Post.create!
post.destroy
assert_equal true, post.destroyed?
Post.insert(post.attributes)
# hard reload
hard_reloaded_post = Post.find(post.id)
assert_equal false, hard_reloaded_post.destroyed?
# soft reload
post.reload
assert_equal false, post.destroyed?
end
end
# Running:
D, [2020-12-12T16:20:27.648498 #2802513] DEBUG -- : TRANSACTION (0.1ms) begin transaction
D, [2020-12-12T16:20:27.648866 #2802513] DEBUG -- : Post Create (0.1ms) INSERT INTO "posts" DEFAULT VALUES
D, [2020-12-12T16:20:27.649118 #2802513] DEBUG -- : TRANSACTION (0.1ms) commit transaction
D, [2020-12-12T16:20:27.649591 #2802513] DEBUG -- : TRANSACTION (0.0ms) begin transaction
D, [2020-12-12T16:20:27.649815 #2802513] DEBUG -- : Post Destroy (0.1ms) DELETE FROM "posts" WHERE "posts"."id" = ? [["id", 1]]
D, [2020-12-12T16:20:27.649978 #2802513] DEBUG -- : TRANSACTION (0.0ms) commit transaction
D, [2020-12-12T16:20:27.650276 #2802513] DEBUG -- : (0.1ms) SELECT sqlite_version(*)
D, [2020-12-12T16:20:27.650834 #2802513] DEBUG -- : Post Insert (0.1ms) INSERT INTO "posts" ("id","title") VALUES (1, NULL) ON CONFLICT DO NOTHING
D, [2020-12-12T16:20:27.651680 #2802513] DEBUG -- : Post Load (0.1ms) SELECT "posts".* FROM "posts" WHERE "posts"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
D, [2020-12-12T16:20:27.652305 #2802513] DEBUG -- : Post Load (0.1ms) SELECT "posts".* FROM "posts" WHERE "posts"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
F
Failure:
BugTest#test_association_stuff [rails_active_record_persistence_reload.rb:48]:
Expected: false
Actual: true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment