Skip to content

Instantly share code, notes, and snippets.

@XrXr
Last active October 11, 2018 23:48
Show Gist options
  • Save XrXr/6cbfbd842e293c4613572c2325320b2d to your computer and use it in GitHub Desktop.
Save XrXr/6cbfbd842e293c4613572c2325320b2d to your computer and use it in GitHub Desktop.
# frozen_string_literal: true
begin
require "bundler/inline"
rescue LoadError => e
$stderr.puts "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" }
# Activate the gem you are reporting the issue against.
gem 'rails', :git => 'https://github.com/rails/rails.git', :ref => '8df7ed3b88fc9f19446d7207a745a331893b81cd' # tip of master atm
gem "sqlite3"
end
require "active_record"
require "minitest/autorun"
require "logger"
# Ensure backward compatibility with minitest 4.
Minitest::Test = MiniTest::Unit::TestCase unless defined?(Minitest::Test)
# 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 :posts, force: true do |t|
end
create_table :comments, force: true do |t|
t.integer :post_id
end
end
class Post < ActiveRecord::Base
has_many :comments, inverse_of: :post
end
class Comment < ActiveRecord::Base
belongs_to :post, inverse_of: :comments
# not strictly necessary since validation fetches all the attributes; this is for being explicit
before_validation do
self.post
end
end
class BugTest < Minitest::Test
def test_saving_parent_and_child_by_using_child
post = Post.new
comment = post.comments.new
comment.post = post # this assign rids comment.association(:post) of inversed status.
# It thinks the parent is stale after post finishes saving.
# there should only be two inserts, but there an extra select
comment.save!
# it also allocates a new instance of the model. This fails.
assert comment.post.equal?(post)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment