CodexBloom - Programming Q&A Platform

implementing using `ActiveModel::Validations` in nested attributes with custom errors in Rails 7

πŸ‘€ Views: 18 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-10
ruby rails activemodel Ruby

I've tried everything I can think of but I've been trying to implement nested attributes for a `User` model that has many `Posts`... I want to validate the posts upon user creation and display custom behavior messages when the validation fails. However, I'm working with some issues where the custom behavior messages aren't being displayed as expected. Here’s a simplified version of my models: ```ruby class User < ApplicationRecord has_many :posts accepts_nested_attributes_for :posts, reject_if: :all_blank validates :name, presence: true end class Post < ApplicationRecord belongs_to :user validates :title, presence: { message: 'must be provided' } validates :content, presence: { message: 'want to be blank' } end ``` In my users controller, I'm permitting the nested attributes like this: ```ruby params.require(:user).permit(:name, posts_attributes: [:title, :content]) ``` I'm trying to create a user with invalid post attributes, like this: ```ruby User.create(name: 'John Doe', posts_attributes: [{ title: '', content: '' }]) ``` However, when I call `user.valid?`, it returns `false` but doesn't populate the errors for the posts. I can see the errors correctly when I call `user.posts.first.errors.full_messages`, but I need those errors to appear in the user object itself. I tried manually adding the errors to the user model using `user.errors.add(:base, post.errors.full_messages)` in a custom validation method, but that feels hacky. Is there a recommended way to handle custom behavior messages for nested attributes in Rails 7? Am I missing something in the validations or behavior handling? Any insights would be appreciated! Thanks for any help you can provide! I'd love to hear your thoughts on this.