Rails 中的计数器缓存:“increment_counter”作品,“增量”;不是吗?
给定三个模型,例如房子、墙和门(房子有多面墙,墙有很多门): House 应该为所有相关墙的所有门设置一个计数器缓存列,因为这是一个相当昂贵的查询。
为了更新本专栏,我在门模型中使用 after_create 和 after_destroy 回调,它们成功触发以下方法:
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”是一种方法:
def house
wall.house
end
最初我使用了稍微不同的方法,但是( IMO)更简单的版本:
def increase_house_doors_count
house.increment(:doors_count)
end
def decrease_house_doors_count
house.decrement(:doors_count)
end
但是后一个版本在模型中使用时没有更新计数器。不过,直接从控制台运行代码是成功的。
我在这里缺少什么?
干杯!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
也许可以这样尝试:
house.increment!(:doors_count)
也许需要就地完成。
Maybe try it like this:
house.increment!(:doors_count)
Perhaps it needs to be done in place.