1

나는 rspec으로 테스트하는 두 개의 간단한 클래스 CompanyVotings을 가지고 있습니다.ActiveRecord counter_cache는 db가 증가하지만 인스턴스가 아닙니다.

나는 그것이 액티브

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

db의 변경 사항을 반영하기 위해 인스턴스를 다시로드해야합니다.

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

와우. 고맙습니다! – Jan

+0

아니, 이건 멋지지 않아! reload는 db에 쿼리를하기 때문에 (불필요 함). 연결된 인스턴스에서 자동으로 업데이트됩니다. – pablo