Conditional Callback scenarios to Run in Rails 7 due to Validation Errors
I'm following best practices but I've searched everywhere and can't find a clear answer... I'm having a frustrating scenario with a conditional callback in my Rails 7 application. I have a `User` model with a `before_save` callback that should only run if the `email` attribute is changed. However, it seems to be failing silently when there are validation errors. Hereโs the code for the callback: ```ruby class User < ApplicationRecord before_save :send_welcome_email, if: :email_changed? validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP } private def send_welcome_email # Logic to send the email end end ``` When I try to create a user with an invalid email, like this: ```ruby user = User.new(email: 'invalid_email') user.save ``` I receive a validation behavior about the email, but the `send_welcome_email` method is never called, which is expected. However, I noticed that if I fix the email and save the user, the callback runs as anticipated. The scenario arises when the user tries to update their email to an invalid format, which should also trigger the callback. For example: ```ruby user = User.find(existing_user_id) user.update(email: 'new_invalid_email') ``` This time, the callback still doesnโt run, and itโs not clear to me how to differentiate between a validation failure due to an invalid email and just the conditional logic of the callback. After digging through the Rails documentation, I couldn't find anything addressing this directly. Is there a way to ensure the callback runs even when validation errors are present? Am I missing something in the callback's setup? Any insights would be greatly appreciated! For context: I'm using Ruby on macOS. Thanks in advance! This is for a mobile app running on Debian. I appreciate any insights! The stack includes Ruby and several other technologies. My development environment is CentOS. What am I doing wrong?