【问题标题】:FactoryGirl doesn't update counter field for associated objectFactoryGirl 不更新关联对象的计数器字段
【发布时间】:2015-12-08 11:37:26
【问题描述】:
class Topic < ActiveRecord::Base
  belongs_to :success_criterion
end

class SuccessCriterion < ActiveRecord::Base
  has_many :topics, dependent: :restrict_with_error
end

SuccessCriterion 管理一个topics_counter 计数器,但使用以下工厂时似乎没有更新:

FactoryGirl.define do
  factory :topic do
    success_criterion { create(:success_criterion) }
    title             'Topic test title'
    intro             'Topic test intro'
    outro             'Topic test outro'
  end
end

看看以下内容:

@topic             = create :topic
@success_criterion = @topic.success_criterion

@success_criterion.topics.any?
=> false
@success_criterion.topics_count
=> 0
@success_criterion.topics.count
=> 1

这里发生了什么?如果没有 topics_counter 字段,它会按预期工作,所以看起来 FactoryGirl 在执行 success_criterion { create(:success_criterion) } 时似乎没有更新计数器。

【问题讨论】:

    标签: ruby-on-rails counter factory-bot


    【解决方案1】:

    您必须在模型中启用counter_cache

    将以下内容添加到您的 Topic 模型中:

    class Topic < ActiveRecord::Base
      belongs_to :success_criterion, counter_cache: true
    end
    

    确保topics_count 列存在于您的SuccessCriterion 模型中。

    Ryan Bates 在他的RailsCasts 中很好地描述了这个功能。

    【讨论】:

    • 愚蠢,愚蠢,愚蠢! ;-) 多年来一直在为 Rails 编程,并提出这样的问题……难以置信!谢谢。
    猜你喜欢
    • 2015-01-12
    • 2013-10-28
    • 2015-02-27
    • 1970-01-01
    • 1970-01-01
    • 2022-11-01
    • 1970-01-01
    • 2016-03-07
    • 1970-01-01
    相关资源
    最近更新 更多