我有两个简单的类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 -> http://railscasts.com/episodes/23-counter-cache-column?view=asciicast中的示例
数据库计数正确,但实例未更新。
我有错误的设置吗?为什么会这样?
非常感谢!