Rails 中的计数器缓存:“increment_counter”作品,“增量”;不是吗?

发布于 2024-10-10 08:57:38 字数 727 浏览 0 评论 0原文

给定三个模型,例如房子、墙和门(房子有多面墙,墙有很多门): 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

油焖大侠 2024-10-17 08:57:38

也许可以这样尝试:

house.increment!(:doors_count)

也许需要就地完成。

Maybe try it like this:

house.increment!(:doors_count)

Perhaps it needs to be done in place.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文