advanced patterns with custom validation in Rails 7.1 models not triggering on save
I recently switched to I have a model in Rails 7.1 where I'm trying to implement a custom validation method... The method should check if a certain attribute is present, but it seems that the validation isn't triggering when I save the record. I’ve defined the validation method and added it as a validation for the model, but the record saves successfully even when the attribute is nil. Here’s the code for my model: ```ruby class User < ApplicationRecord validates :username, presence: true, uniqueness: true validate :custom_username_validation def custom_username_validation errors.add(:username, 'must be at least 5 characters long') if username.present? && username.length < 5 end end ``` When I try to create a new user with a username shorter than 5 characters, it saves successfully, which is not the expected behavior. This is the code I'm using to create the user: ```ruby User.create(username: 'abc') ``` Shouldn't the custom validation prevent the record from being saved? I’ve tried using `valid?` before saving the record and it correctly adds the behavior, but I don’t understand why it’s still saving. I’ve also checked that the model is not skipped in some way due to other callbacks. Any help would be greatly appreciated! What am I missing here? I recently upgraded to Ruby 3.9. Any ideas how to fix this? I'm working in a Ubuntu 22.04 environment. Thanks for any help you can provide!