我有两个简单的类Company
和Votings
我用rspec测试。
当我向公司添加投票时,它会被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 cast的例子 - &gt; http://railscasts.com/episodes/23-counter-cache-column?view=asciicast
数据库计算正确,但实例未更新。
我的设置有误吗? 为什么这样做?
非常感谢!答案 0 :(得分:0)
您需要重新加载实例以反映db中的更改。
# ...
c.save
c.votings.create(Fabricate.attributes_for :voting)
# Add this line
c.reload
c.votings_count.should == 1