Skip to content

Instantly share code, notes, and snippets.

@joslynesser
Created August 29, 2011 03:00
Show Gist options
  • Save joslynesser/1177686 to your computer and use it in GitHub Desktop.
Save joslynesser/1177686 to your computer and use it in GitHub Desktop.
ruby-1.9.2-p180 :001 > p = Post.create
=> #<Post id: 1, title: nil, comments_count: 0, created_at: "2011-08-29 02:58:04", updated_at: "2011-08-29 02:58:04">
ruby-1.9.2-p180 :002 > p.comments.create
=> #<Comment id: 1, title: nil, post_id: 1, created_at: "2011-08-29 02:58:16", updated_at: "2011-08-29 02:58:16">
ruby-1.9.2-p180 :003 > p.comments.create
=> #<Comment id: 2, title: nil, post_id: 1, created_at: "2011-08-29 02:58:18", updated_at: "2011-08-29 02:58:18">
ruby-1.9.2-p180 :004 > p.reload
=> #<Post id: 1, title: nil, comments_count: 2, created_at: "2011-08-29 02:58:04", updated_at: "2011-08-29 02:58:04">
ruby-1.9.2-p180 :005 > Post.create
=> #<Post id: 2, title: nil, comments_count: 0, created_at: "2011-08-29 02:58:30", updated_at: "2011-08-29 02:58:30">
ruby-1.9.2-p180 :006 > c = Comment.last
=> #<Comment id: 2, title: nil, post_id: 1, created_at: "2011-08-29 02:58:18", updated_at: "2011-08-29 02:58:18">
# Omg the following updates counters without the record being saved!
ruby-1.9.2-p180 :007 > c.post = Post.last
=> #<Post id: 2, title: nil, comments_count: 0, created_at: "2011-08-29 02:58:30", updated_at: "2011-08-29 02:58:30">
# Omg notice the counts are off!
ruby-1.9.2-p180 :008 > p.reload
=> #<Post id: 1, title: nil, comments_count: 1, created_at: "2011-08-29 02:58:04", updated_at: "2011-08-29 02:58:04">
ruby-1.9.2-p180 :009 > p.comments.count
=> 2
class Post < ActiveRecord::Base
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :post, :counter_cache => true
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment