1

我有兩個簡單的類CompanyVotings,我用rspec測試。ActiveRecord counter_cache遞增db但不是實例

當我投票給它添加得到由一個ActiveRecord

class Company < ActiveRecord::Base 
    attr_accessible :name, :votings_count 
    has_many :votings, :dependent => :destroy 
end 

計數的公司和這個投票類:

class Voting < ActiveRecord::Base 
    attr_accessible :percent, :company, :company_id 

    belongs_to :company, counter_cache: true 
end 

這種簡單的RSpec

require 'spec_helper' 

describe Company do 
    it "should count the votings in a table" do 
    c = Company.new(Fabricate.attributes_for :company) 
    c.save 
    c.votings.create(Fabricate.attributes_for :voting) 
    c.votings_count.should == 1 
    end 
end 
#expected: 1 
#got: 0 (using ==) 

列不是零。默認值= 0

add_column :companies, :votings_count, :integer, default: 0 

我已經按照從ryans counter_cache投的例子 - >http://railscasts.com/episodes/23-counter-cache-column?view=asciicast

的DB是正確計數,但實例不更新。

我的設置有誤嗎? 爲什麼這樣表現?

非常感謝!

回答

0

您需要重新加載實例以反映數據庫中的更改。

# ... 
c.save 
c.votings.create(Fabricate.attributes_for :voting) 
# Add this line 
c.reload 
c.votings_count.should == 1 
+0

太酷了。謝謝! – Jan

+0

不,這不太酷!因爲重新加載對db進行查詢(這是不必要的)。它應該在關聯的實例中自動更新。 – pablo