Skip to content

Instantly share code, notes, and snippets.

@gkats
Last active August 29, 2015 14:11
Show Gist options
  • Save gkats/b66d6ad64ead24ed07ec to your computer and use it in GitHub Desktop.
Save gkats/b66d6ad64ead24ed07ec to your computer and use it in GitHub Desktop.
Possible bug in activerecord has_one
gem 'activerecord', '4.1.8'
# The behavior is the same with 4.2.0.rc3 as well
# gem 'activerecord', '4.2.0.rc3'
gem 'sqlite3'
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:')
# Disable sql logging
# ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Schema.define do
create_table :posts do |t|
end
create_table :comments do |t|
t.integer :post_id
end
create_table :qualities do |t|
t.integer :post_id
end
end
class Post < ActiveRecord::Base
has_many :comments
has_one :quality
end
class Comment < ActiveRecord::Base
belongs_to :post
end
class Quality < ActiveRecord::Base
belongs_to :post
end
class BugTest < Minitest::Test
def test_new_object_with_has_many
clear_database
post = Post.create!
post.comments << Comment.create!
new_post = Post.new(id: post.id)
assert_equal Comment.first, new_post.comments.first
end
def test_reloaded_object_with_has_one
clear_database
post = Post.create!
post.quality = Quality.create!
new_post = Post.new(id: post.id)
assert_equal Quality.first, new_post.reload.quality
end
# This fails
def test_new_object_with_has_one
clear_database
post = Post.create!
post.quality = Quality.create!
new_post = Post.new(id: post.id)
assert_equal Quality.first, new_post.quality
end
private
def clear_database
Post.destroy_all
Comment.destroy_all
Quality.destroy_all
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment