advanced patterns when using a custom after_save callback in Rails 7.1 with nested attributes
I'm a bit lost with I'm sure I'm missing something obvious here, but I'm working with an scenario with a custom `after_save` callback in my Rails 7.1 application that uses nested attributes. I have a `User` model that has many `Posts`, and I'm trying to update a count of the posts after a user is saved. However, it seems like the callback is being triggered multiple times, and I'm getting unexpected results. Hereโs a simplified version of my model: ```ruby class User < ApplicationRecord has_many :posts, dependent: :destroy accepts_nested_attributes_for :posts after_save :update_post_count private def update_post_count self.post_count = posts.count save if post_count_changed? end end ``` I'm calling it like this in my controller: ```ruby class UsersController < ApplicationController def create @user = User.new(user_params) if @user.save redirect_to @user, notice: 'User was successfully created.' else render :new end end private def user_params params.require(:user).permit(:name, posts_attributes: [:title, :body]) end end ``` The question arises when I create a user with multiple posts at once. I expect the `post_count` to equal the number of posts created, but I see that the count sometimes doubles or does not reflect the correct number at all. The behavior I receive is `ActiveRecord::RecordNotSaved: Failed to save the record: Post count is invalid`. Iโve tried adding a guard clause to prevent the `update_post_count` method from running if the user is a new record, but that didnโt resolve the scenario. Any insights on why this might be happening or how to ensure the count is accurate? Iโm also concerned about performance implications if this callback is being triggered unnecessarily, especially with many nested attributes. I'm working on a service that needs to handle this. Thanks in advance! I'm working on a application that needs to handle this. Any ideas how to fix this?