Last active
August 29, 2015 13:57
-
-
Save jonastemplestein/9808571 to your computer and use it in GitHub Desktop.
BUG: counter_cache updates counter twice on assignment
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
unless File.exist?('Gemfile') | |
File.write('Gemfile', <<-GEMFILE) | |
source 'https://rubygems.org' | |
gem 'rails', github: 'rails/rails' | |
gem 'arel', github: 'rails/arel' | |
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 :posts do |t| | |
t.integer :comments_count | |
end | |
create_table :comments do |t| | |
t.integer :post_id | |
end | |
end | |
class Post < ActiveRecord::Base | |
has_many :comments | |
end | |
class Comment < ActiveRecord::Base | |
belongs_to :post, counter_cache: true | |
end | |
class BugTest < Minitest::Test | |
def test_update_from_nil | |
post = Post.create! | |
comment = Comment.create! | |
comment.post = post # this line causes the first increment | |
comment.save! | |
# NOTE: this doesn't work either | |
#comment.update_attributes(post: post) | |
# POW, comments_count is 2 | |
assert_equal 1, post.reload.comments_count | |
end | |
# note that the bug doesn't occur when updating a comment that was | |
# previously assigned to another post | |
def test_update_from_other_post | |
post = Post.create! | |
post2 = Post.create! | |
comment = Comment.create!(post: post) | |
assert_equal 1, post.reload.comments_count | |
assert_equal nil, post2.reload.comments_count | |
comment.post = post2 | |
comment.save! | |
# POW, comments_count is 2 | |
assert_equal 0, post.reload.comments_count | |
assert_equal 1, post2.reload.comments_count | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment