Joshua Muheim
Joshua Muheim

Reputation: 13233

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 manages a topics_counter counter, but it doesn't seem to be updated when using the following factory:

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

Take a look at the following:

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

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

What's happening here? Without the topics_counter field, it works as expected, so it seems the FactoryGirl doesn't seem to update the counter when doing success_criterion { create(:success_criterion) }.

Upvotes: 1

Views: 47

Answers (1)

Tobias
Tobias

Reputation: 4653

You have to enable counter_cache in your model.

Add the following to your Topic model:

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

Be sure that the topics_count column is present in your SuccessCriterion model.

Ryan Bates described this feature very well in one of his RailsCasts.

Upvotes: 1

Related Questions