[英]FactoryGirl doesn't update counter field for associated object
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) }
時似乎並未更新計數器。
您必須在模型中啟用counter_cache
。
將以下內容添加到您的Topic
模型:
class Topic < ActiveRecord::Base
belongs_to :success_criterion, counter_cache: true
end
確保SuccessCriterion
模型中包含topics_count
列。
瑞安貝茨( Ryan Bates)在他的RailsCast中很好地描述了這個功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.