【问题标题】:ActiveRecord counter_cache increments db but not instanceActiveRecord counter_cache 增加 db 但不增加实例
【发布时间】:2013-09-24 12:58:37
【问题描述】:

我有两个简单的类 CompanyVotings 用 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

数据库计数正确,但实例未更新。

我的设置有误吗? 为什么会这样?

非常感谢!

【问题讨论】:

    标签: activerecord ruby-on-rails-3.2 rspec2 ruby-1.9.3 counter-cache


    【解决方案1】:

    您需要重新加载实例以反映 db 中的更改。

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

    【讨论】:

    • 不,这不酷!因为重新加载对 db 进行查询(这是不必要的)。它应该在关联的实例中自动更新。
    猜你喜欢
    • 1970-01-01
    • 2020-05-15
    • 2016-10-09
    • 1970-01-01
    • 1970-01-01
    • 2020-03-30
    • 1970-01-01
    • 2013-04-08
    • 1970-01-01
    相关资源
    最近更新 更多