Created
December 8, 2011 08:08
-
-
Save tmeasday/1446430 to your computer and use it in GitHub Desktop.
Problem with has_many :through counter_caches
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
require 'rubygems' | |
require 'active_record' | |
# Print out what version we're running | |
puts "Active Record #{ActiveRecord::VERSION::STRING}" | |
# Connect to an in-memory sqlite3 database | |
ActiveRecord::Base.establish_connection( | |
:adapter => 'sqlite3', | |
:database => ':memory:' | |
) | |
# Create the minimal database schema necessary to reproduce the bug | |
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 | |
# define the models | |
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 | |
end | |
### Here's the bugs: | |
user = User.create | |
project = Project.create | |
puts "Initially:" | |
puts "User's projects_count is #{user.projects_count}" | |
puts "Projects's users_count is #{project.users_count}" | |
user.projects << project | |
puts "After adding the project once:" | |
puts "User's projects_count is #{user.projects_count}" | |
puts "Projects's users_count is #{project.users_count}" | |
user.projects << project | |
puts "After adding the project a second time:" | |
puts "User's projects_count is #{user.projects_count}" | |
puts "Projects's users_count is #{project.users_count}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output is: