Commit b36c90e33030f30d889eb37d0234d116844297fc
1 parent
695de2bb
Exists in
master
and in
1 other branch
Problem#comments counter cache
Showing
6 changed files
with
53 additions
and
2 deletions
Show diff stats
app/models/comment.rb
| ... | ... | @@ -2,12 +2,25 @@ class Comment |
| 2 | 2 | include Mongoid::Document |
| 3 | 3 | include Mongoid::Timestamps |
| 4 | 4 | |
| 5 | + after_create :increase_counter_cache | |
| 6 | + before_destroy :decrease_counter_cache | |
| 7 | + | |
| 5 | 8 | field :body, :type => String |
| 6 | 9 | index :user_id |
| 7 | 10 | |
| 8 | - belongs_to :err | |
| 11 | + belongs_to :err, :class_name => "Problem" | |
| 9 | 12 | belongs_to :user |
| 10 | 13 | |
| 11 | 14 | validates_presence_of :body |
| 15 | + | |
| 16 | + protected | |
| 17 | + def increase_counter_cache | |
| 18 | + err.inc(:comments_count, 1) | |
| 19 | + end | |
| 20 | + | |
| 21 | + def decrease_counter_cache | |
| 22 | + err.inc(:comments_count, -1) if err | |
| 23 | + end | |
| 24 | + | |
| 12 | 25 | end |
| 13 | 26 | ... | ... |
app/models/problem.rb
| ... | ... | @@ -21,6 +21,7 @@ class Problem |
| 21 | 21 | field :user_agents, :type => Array, :default => [] |
| 22 | 22 | field :messages, :type => Array, :default => [] |
| 23 | 23 | field :hosts, :type => Array, :default => [] |
| 24 | + field :comments_count, :type => Integer, :default => 0 | |
| 24 | 25 | |
| 25 | 26 | index :app_id |
| 26 | 27 | index :app_name | ... | ... |
app/views/errs/_table.html.haml
spec/factories/comment_factories.rb
spec/models/problem_spec.rb
| ... | ... | @@ -276,5 +276,31 @@ describe Problem do |
| 276 | 276 | end |
| 277 | 277 | end |
| 278 | 278 | |
| 279 | + context "comment counter cache" do | |
| 280 | + before do | |
| 281 | + @app = Factory(:app) | |
| 282 | + @problem = Factory(:problem, :app => @app) | |
| 283 | + end | |
| 284 | + | |
| 285 | + it "#comments_count returns 0 by default" do | |
| 286 | + @problem.comments_count.should == 0 | |
| 287 | + end | |
| 288 | + | |
| 289 | + it "adding a comment increases #comments_count by 1" do | |
| 290 | + lambda { | |
| 291 | + Factory(:comment, :err => @problem) | |
| 292 | + }.should change(@problem, :comments_count).from(0).to(1) | |
| 293 | + end | |
| 294 | + | |
| 295 | + it "removing a comment decreases #comments_count by 1" do | |
| 296 | + comment1 = Factory(:comment, :err => @problem) | |
| 297 | + lambda { | |
| 298 | + @problem.reload.comments.first.destroy | |
| 299 | + @problem.reload | |
| 300 | + }.should change(@problem, :comments_count).from(1).to(0) | |
| 301 | + end | |
| 302 | + end | |
| 303 | + | |
| 304 | + | |
| 279 | 305 | end |
| 280 | 306 | ... | ... |