implementing Custom Validations in ActiveModel: advanced patterns on Nested Attributes
I've been struggling with this for a few days now and could really use some help. I'm working with a strange scenario while implementing custom validations in my Rails 7 application using ActiveModel. I have a model for a `User` that accepts nested attributes for their associated `Profile`. The `Profile` model has a custom validation that should ensure the `bio` field is at least 50 characters long, but it seems to be bypassed when I attempt to create or update a `User` with nested `Profile` attributes. Hereβs how my `User` and `Profile` models are structured: ```ruby class User < ApplicationRecord has_one :profile, dependent: :destroy accepts_nested_attributes_for :profile end class Profile < ApplicationRecord belongs_to :user validate :bio_length private def bio_length if bio.present? && bio.length < 50 errors.add(:bio, 'must be at least 50 characters long') end end end ``` When I try to create a user with a short bio, I expect the validation to unexpected result, but it doesn't. Here's the code I use to create the user: ```ruby user = User.new( email: 'test@example.com', profile_attributes: { bio: 'Short bio' } ) if user.save puts 'User created successfully' else puts user.errors.full_messages end ``` Instead of getting the expected validation behavior, I see 'User created successfully' printed. I've checked that the `Profile` instance is being built correctly and that the validation method is defined. I also ensured that the `profile_attributes` are permitted in the controller. I'm puzzled as to why the validation isn't triggering. Any insights or suggestions on what I might be missing? I've tried using `valid?` on the `User` instance before saving, and that returns `false` as expected, but it still saves the user without the profile validation kicking in. Is there a specific configuration or best practice I should follow to ensure custom validations on nested attributes are respected? Iβm using Ruby 3.1 and Rails 7.0.3. What's the best practice here?