Counter cache in Rails: 'increment_counter' works, 'increment' doesn't?
Given three models, e.g, house, wall and door (a house has may walls and a wall has many doors): House should have a counter cache column for all doors of all associated walls, since that's a fairly expensive query to make.
In order to update this column, I'm using after_create and after_destroy callbacks within the door model, which trigger the following methods successfully:
def increase_house_doors_count
House.increment_counter(:doors_count, house.id)
end
def decrease_house_doors_count
House.decrement_counter(:doors_count, house.id)
end
"house" is a method:
def house
wall.house
end
Initially I had used a slightly different but (IMO) more simple version:
def increase_house_doors_count
house.increment(:doors_count)
end
def decrease_house_doors_count
house.decrement(:doors_count)
end
But this latter version didn't update the counter when 开发者_高级运维used within the model. Running the code directly from the console was successful, though.
What am i missing here?
Cheers!
Maybe try it like this:
house.increment!(:doors_count)
Perhaps it needs to be done in place.
精彩评论