Skip to content

Instantly share code, notes, and snippets.

@pjambet
Created February 9, 2023 19:10
Show Gist options
  • Save pjambet/d84d460a5f316964b6c186acf8b38e83 to your computer and use it in GitHub Desktop.
Save pjambet/d84d460a5f316964b6c186acf8b38e83 to your computer and use it in GitHub Desktop.
Rails 7.0 update_counter & scope issue
# frozen_string_literal: true
require "bundler/inline"
gemfile(true) do
source "https://rubygems.org"
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
gem "rails", github: "rails/rails", branch: "main"
gem "sqlite3"
end
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, force: true do |t|
end
create_table :comments, force: true do |t|
t.integer :post_id
t.integer :views_count, default: 0, null: false
end
end
class Post < ActiveRecord::Base
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :post
default_scope -> { where(post_id: 1) }
end
class BugTest < Minitest::Test
def test_association_stuff
post1 = Post.create!
comment1 = post1.comments.create!(views_count: 10)
post2 = Post.create!
comment2 =post2.comments.create!(views_count: 10)
comment_ids = [comment1.id, comment2.id]
Comment.update_counters(comment_ids, views_count: -10)
assert_equal 0, comment1.reload.views_count
assert_equal 10, comment2.reload.views_count
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment