Skip to content

Instantly share code, notes, and snippets.

@arturopie
Created November 22, 2014 15:15
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 arturopie/d389020b327c594a32c9 to your computer and use it in GitHub Desktop.
Save arturopie/d389020b327c594a32c9 to your computer and use it in GitHub Desktop.
Rails bug when setting association using same child record, but different child instances
unless File.exist?('Gemfile')
File.write('Gemfile', <<-GEMFILE)
source 'https://rubygems.org'
gem 'rails', github: 'rails/rails'
gem 'arel', github: 'rails/arel'
gem 'rack', github: 'rack/rack'
gem 'i18n', github: 'svenfuchs/i18n'
gem 'sqlite3'
GEMFILE
system 'bundle'
end
require 'bundler'
Bundler.setup(:default)
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 "comments", :force => true do |t|
t.integer "post_id"
t.string "text"
end
create_table "posts", :force => true do |t|
end
end
class Post < ActiveRecord::Base
has_many :comments
end
class Comment < ActiveRecord::Base
end
class BugTest < ActiveSupport::TestCase
test "updates association when using same child record, but different child instances" do
post = Post.create(
comments: [Comment.create(text: 'old text')]
)
comment = Comment.find(post.comments.first.id)
assert_not_equal post.comments.first.object_id, comment.object_id # this is required to reproduce bug.
comment.text = 'new text'
post.comments = [comment]
assert_equal 'new text', post.comments.first.text
# it fails:
# 1) Failure:
# BugTest#test_updates_association_when_using_same_child_record,_but_different_child_instances [association_bug.rb:54]:
# Expected: "new text"
# Actual: "old text"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment