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
I have two models student and school with one to many relationship:
When I try update student (which doesn't belong to any school) with school with below code:
Counter cache student.school_count is incremented twice time.
When I replace above code with:
@school.students << studentIt works fine.
Rails version: 4.2.5.1
Ruby version: 2.3.0