Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
unless File.exists?('Gemfile')
File.write('Gemfile', <<-GEMFILE)
source 'https://rubygems.org'
gem 'rails', github: 'rails/rails'
gem 'sqlite3'
GEMFILE
system 'bundle'
end
require 'bundler'
Bundler.setup(:default)
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, :force => true do |t|
t.integer :projects_count, :default => 0
end
create_table :projects, :force => true do |t|
t.integer :users_count, :default => 0
end
create_table :memberships, :force => true do |t|
t.integer :user_id
t.integer :project_id
end
end
class User < ActiveRecord::Base
has_many :memberships
has_many :projects, :through => :memberships
end
class Project < ActiveRecord::Base
has_many :memberships
has_many :users, :through => :memberships
end
class Membership < ActiveRecord::Base
belongs_to :user
belongs_to :project, counter_cache: :users_count
end
class BugTest < MiniTest::Unit::TestCase
def test_case
Membership.delete_all
user = User.create
project = Project.create
assert_equal 0, user.projects_count
assert_equal 0, project.users_count
user.projects << project
user.reload
project.reload
assert_equal 1, user.projects_count
assert_equal 1, project.users_count
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment