更新模型时如何更新 counter_cache? [英] How to update counter_cache when updating a model?

查看:30
本文介绍了更新模型时如何更新 counter_cache?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的关系:

class Item
  belongs_to :container, :counter_cache => true
end

class Container
  has_many :items
end

假设我有两个容器.我创建了一个项目并将其与第一个容器相关联.计数器增加.

Let's say I have two containers. I create an item and associate it with the first container. The counter is increased.

然后我决定将它与另一个容器相关联.如何更新两个容器的 items_count 列?

Then I decide to associate it with the other container instead. How to update the items_count column of both containers?

我在 http://railsforum.com/viewtopic.php?id= 找到了一个可能的解决方案39285 .. 但是我是初学者,我不明白.这是唯一的方法吗?

I found a possible solution at http://railsforum.com/viewtopic.php?id=39285 .. however I'm a beginner and I don't understand it. Is this the only way to do it?

推荐答案

它应该自动工作.当您更新 items.container_id 时,它会减少旧容器的计数器并增加新容器的计数器.但如果它不起作用 - 这很奇怪.你可以试试这个回调:

It should work automatically. When you are updating items.container_id it will decreament old container's counter and increament new one. But if it isn't works - it is strange. You can try this callback:

class Item
  belongs_to :container, :counter_cache => true
  before_save :update_counters

  private
  def update_counters
    new_container = Container.find self.container_id
    old_container = Container.find self.container_id_was
    new_container.increament(:items_count)
    old_container.decreament(:items_count)
  end
end

UPD

展示原生行为:

container1 = Container.create :title => "container 1"
#=> #<Container title: "container 1", :items_count: nil>
container2 = Container.create :title => "container 2"
#=> #<Container title: "container 2", :items_count: nil>
item = container1.items.create(:title => "item 1")
Container.first
#=> #<Container title: "container 1", :items_count: 1>
Container.last
#=> #<Container title: "container 1", :items_count: nil>
item.container = Container.last
item.save
Container.first
#=> #<Container title: "container 1", :items_count: 0>
Container.last
#=> #<Container title: "container 1", :items_count: 1>

所以它应该可以在没有任何黑客攻击的情况下工作.从盒子里.

So it should work without any hacking. From the box.

这篇关于更新模型时如何更新 counter_cache?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆