Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
gem 'activerecord', '4.1.5'
require 'active_record'
require 'minitest/autorun'
require 'logger'
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Schema.define do
create_table :users do |t|
t.integer :saved_count
t.timestamps
end
create_table :profiles do |t|
t.integer :user_id
t.integer :post_id
t.timestamps
end
create_table :posts do |t|
t.string :content
t.timestamps
end
end
class User < ActiveRecord::Base
has_many :profiles
has_many :posts, through: :profiles
before_save -> { increment :saved_count }
end
class Profile < ActiveRecord::Base
belongs_to :user
belongs_to :post
end
class Post < ActiveRecord::Base
has_one :profile
has_one :user, through: :profile
end
class BugTest < MiniTest::Unit::TestCase
def test_saving_post_does_not_save_user_when_relation_is_not_referenced
user = User.create!
post = Post.create!(content: 'foo')
profile = Profile.create!(post: post, user: user)
post.save
assert_equal 1, user.reload.saved_count
# if we do not reference post.user, then the user is not touched (correct)
post.save
assert_equal 1, user.reload.saved_count
end
def test_saving_post_does_not_save_user_when_relation_is_referenced
user = User.create!
post = Post.create!(content: 'foo')
profile = Profile.create!(post: post, user: user)
post.save
assert_equal 1, user.reload.saved_count
post.user # necessary to create the reference
# but now post.save will also save user even though there are no changes
post.save
assert_equal 1, user.reload.saved_count
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment