Skip to content

counter_cache is incremented twice times #24183

@mikgry

Description

@mikgry

I have two models student and school with one to many relationship:

class School < ActiveRecord::Base
  has_many :students, inverse_of: :school

  validates :name, presence: true, uniqueness: true
end

class Student < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :recoverable, :rememberable, :trackable, :validatable, :invitable

  include ActiveUser

  attr_accessor :inviting # flag used for conditional validations

  belongs_to :school, counter_cache: true

  delegate :name, to: :school, prefix: 'school', allow_nil: true

  validates :password, password_complexity: true, if: :password_required?

  private

  def password_required?
    inviting ? false : super
  end
end

When I try update student (which doesn't belong to any school) with school with below code:

student.school = @school
student.save(validate: false)

Counter cache student.school_count is incremented twice time.
When I replace above code with:

@school.students << student

It works fine.

Rails version: 4.2.5.1
Ruby version: 2.3.0

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions