Skip to content

Instantly share code, notes, and snippets.

@roychri
Created November 12, 2012 15:38
Show Gist options
  • Save roychri/4060031 to your computer and use it in GitHub Desktop.
Save roychri/4060031 to your computer and use it in GitHub Desktop.
:counter_cache finally working
# db/migrate/20121112152734_create_users.rb
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :name
t.integer :groups_count, :default => 0
t.timestamps
end
end
end
# db/migrate/20121112152847_create_user_groups.rb
class CreateUserGroups < ActiveRecord::Migration
def change
create_table :user_groups do |t|
t.string :name
t.integer :user_id
t.timestamps
end
end
end
# From the console I run
$ rails console
1.9.3p194 :001 > user = User.create :name => "joe"
(0.0ms) begin transaction
SQL (3.2ms) INSERT INTO "users" ("created_at", "groups_count", "name", "updated_at") VALUES (?, ?, ?, ?) [["created_at", Mon, 12 Nov 2012 18:57:54 UTC +00:00], ["groups_count", 0], ["name", "joe"], ["updated_at", Mon, 12 Nov 2012 18:57:54 UTC +00:00]]
(12.0ms) commit transaction
=> #<User id: 3, name: "joe", groups_count: 0, created_at: "2012-11-12 18:57:54", updated_at: "2012-11-12 18:57:54">
1.9.3p194 :002 > user.groups.size
=> 0
1.9.3p194 :003 >
# Now the size method does not execute an SQL query
# app/models/user.rb
class User < ActiveRecord::Base
attr_accessible :name
has_many :groups, :class_name => "UserGroup", :inverse_of => :user, :foreign_key => "user_id"
end
# app/models/user_group.rb
class UserGroup < ActiveRecord::Base
attr_accessible :name, :user_id
belongs_to :user, :counter_cache => :groups_count, :inverse_of => :groups, :foreign_key => "user_id"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment