0

我有一个要使用 counter_cache 的 Padrino 应用程序。我使用 ActiveRecord 作为我的 ORM。在我的存储库模型中,我想记录与给定存储库关联的贡献数量。以下是相关型号:

class Repository < ActiveRecord::Base

  has_many :contributions, autosave: true
  has_many :users, through: :contributions

  validates :full_name, presence: true, uniqueness: true

end

class Contribution < ActiveRecord::Base

  belongs_to :user
  belongs_to :repository, counter_cache: true

end 

class User < ActiveRecord::Base

  has_many :contributions
  has_many :repositories, through: :contributions

  validates :username, presence: true, uniqueness: true

end

架构如下:

  create_table "contributions", :force => true do |t|
    t.integer  "user_id"
    t.integer  "repository_id"
  end

  create_table "repositories", :force => true do |t|
    t.string   "full_name"
    t.integer  "contributions_count", :default => 0
  end

  create_table "users", :force => true do |t|
    t.string   "username"
  end

我在 Rspec 中创建了一个测试来检查贡献计数是否正确更新。但是,我无法让它通过。这是规格:

  describe "when a new contribution is created" do
    it "updates the counter cache" do
      repo = Repository.create(full_name: "sample_repo")
      user = User.create(username: "sample_user")
      expect {
        Contribution.create(user: user, repository: repo)
        }.to change {repo.contributions_count }.by(1)
      end
    end

当我运行规范时,出现以下故障:

  1) Repository when a new contribution is created updates the counter cache
     Failure/Error: expect {
       result should have been changed by 1, but was changed by 0
     # ./spec/models/repository_spec.rb:43:in `block (3 levels) in <top (required)>'

我也尝试在控制台中创建贡献,它没有更新存储库 counter_cache。我已经尝试了很多东西,但似乎无法弄清楚如何让它正常工作。任何帮助,将不胜感激。谢谢。

4

1 回答 1

1

我认为这是因为当对象被保存到数据库repo时,Ruby 并没有神奇地更新你的对象。Contribution您将需要从数据库中重新加载信息:

repo.reload.contributions_count
于 2013-08-15T03:58:08.010 回答