使用Rails的3.1.3,我想弄清楚爲什麼我們的計數器緩存沒有正確更新時通過update_attributes更改父記錄的id。Rails的counter_cache沒有正確更新
class ExhibitorRegistration < ActiveRecord::Base
belongs_to :event, :counter_cache => true
end
class Event < ActiveRecord::Base
has_many :exhibitor_registrations, :dependent => :destroy
end
describe ExhibitorRegistration do
it 'correctly maintains the counter cache on events' do
event = Factory(:event)
other_event = Factory(:event)
registration = Factory(:exhibitor_registration, :event => event)
event.reload
event.exhibitor_registrations_count.should == 1
registration.update_attributes(:event_id => other_event.id)
event.reload
event.exhibitor_registrations_count.should == 0
other_event.reload
other_event.exhibitor_registrations_count.should == 1
end
end
此規範失敗,指示事件計數器緩存未遞減。
1) ExhibitorRegistration correctly maintains the counter cache on events
Failure/Error: event.exhibitor_registrations_count.should == 0
expected: 0
got: 1 (using ==)
我應該甚至期望這個工作或我需要手動跟蹤更改並更新自己的櫃檯?
Thanks @ mu-is-too-short這絕對可以解決這個問題。我認爲這在ActiveRecord本身當然值得關注,我會考慮提交補丁。 – 2012-02-23 13:02:25
@MichaelGuterl:很酷,別忘了在你的補丁中包含一個文檔更新:) – 2012-02-23 14:48:28
@MichaelGuterl:你也可以嘗試Ben的方法。我要再次檢查Rails代碼,看看我是否錯過了任何東西。這可能只是一個錯誤和糟糕/不完整的文檔。 – 2012-02-24 04:22:22