Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Rails counter cache
# frozen_string_literal: true
# Please include only the minimum code necessary to reproduce your issue.
require "bundler/inline"
# STEP ONE: What versions are you using?
gemfile(true) do
ruby "2.5.1"
source "https://rubygems.org"
gem "activerecord", "4.2.11"
gem "minitest", "5.11.3"
gem "sqlite3", "1.3.13"
end
require "active_record"
require "minitest/autorun"
require "logger"
# Please use sqlite for your bug reports, if possible.
ActiveSupport.test_order = :sorted
ActiveRecord::Base.raise_in_transactional_callbacks = true
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
ActiveRecord::Base.logger = nil
ActiveRecord::Base.logger = nil
ActiveRecord::Schema.define do
# STEP TWO: Define your tables here.
create_table :users, force: true do |t|
t.text :name, null: false
t.integer :comments_count, default: 0, null: false
t.timestamps null: false
end
create_table :comments, force: true do |t|
t.integer :user_id, null: false, index: true
t.text :body, null: false
t.timestamps null: false
end
create_table :versions do |t|
t.string :item_type, null: false
t.integer :item_id, null: false
t.string :event, null: false
t.string :whodunnit
t.text :object, limit: 1_073_741_823
t.text :object_changes, limit: 1_073_741_823
t.datetime :created_at
end
add_index :versions, %i[item_type item_id]
end
ActiveRecord::Base.logger = Logger.new(STDOUT)
# STEP FOUR: Define your AR models here.
class User < ActiveRecord::Base
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :user, counter_cache: true
end
# STEP FIVE: Please write a test that demonstrates your issue.
class BugTest < ActiveSupport::TestCase
def test_counter_cache
# Expected to return 0
user = User.create!(name: "Jhon")
user.reload
assert_equal 0, user.comments_count
assert_equal 0, user.comments.size
# Expected to return 1
user.comments.create!(body: 'Nice!')
user.reload
assert_equal 1, user.comments_count
assert_equal 1, user.comments.size
# Expected to return 12345
user = User.create!(name: "Jhon", comments_count: 12345)
user.reload
assert_equal 12345, user.comments_count
assert_equal 12345, user.comments.size
end
end
# STEP SIX: Run this script using `ruby bug_report.rb`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.