【问题标题】:Cannot Get Counter_Cache to update properly in Padrino (Rails)无法在 Padrino (Rails) 中正确更新 Counter_Cache
【发布时间】:2013-08-15 03:31:49
【问题描述】:

我有一个我正在构建的 Padrino 应用程序,我想在其中使用 counter_cache。我使用 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。我已经尝试了很多东西,但似乎无法弄清楚如何让它正常工作。任何帮助,将不胜感激。谢谢。

【问题讨论】:

    标签: ruby-on-rails ruby activerecord rspec padrino


    【解决方案1】:

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

    repo.reload.contributions_count
    

    【讨论】:

    • 我按照建议更新了代码,但现在我收到以下错误Failure/Error: repo.reload.contributions_count ActiveRecord::RecordNotFound: Couldn't find Repository without an ID
    猜你喜欢
    • 1970-01-01
    • 2017-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-08
    • 1970-01-01
    相关资源
    最近更新 更多