CodexBloom - Programming Q&A Platform

Rails 7: How to Correctly Handle Nested Attributes with Custom Validation?

👀 Views: 3 💬 Answers: 1 📅 Created: 2025-06-08
ruby-on-rails activerecord validation Ruby

I'm upgrading from an older version and I'm upgrading from an older version and I'm writing unit tests and I tried several approaches but none seem to work. Quick question that's been bugging me - I'm working on a project and hit a roadblock... I have a Rails 7 application where I need to deal with nested attributes in a form. I have a `Post` model that has many `Comments`, and I want to allow users to create a post along with its comments in one form using nested attributes. However, I'm working with issues when it comes to validating the comments before saving the post. I’ve set up the following code in my `Post` model: ```ruby class Post < ApplicationRecord has_many :comments, dependent: :destroy accepts_nested_attributes_for :comments, allow_destroy: true, reject_if: :all_blank validates :title, presence: true validates_associated :comments end ``` In my `Comment` model, I have: ```ruby class Comment < ApplicationRecord belongs_to :post validates :content, presence: true end ``` When I submit the form with both post and comment data, I often get validation errors for comments that are not properly handled. For example, if a comment's content is blank, I want the entire post saving to unexpected result, but the comment still shows up in the behavior messages. Here's how I handle the form submission in my controller: ```ruby class PostsController < ApplicationController def create @post = Post.new(post_params) if @post.save redirect_to @post, notice: 'Post was successfully created.' else render :new end end private def post_params params.require(:post).permit(:title, comments_attributes: [:id, :content, :_destroy]) end end ``` When I test it, if I leave the comment field blank, I get the behavior message `"Comments content need to be blank"` but the post is still created, which isn't the expected behavior. I’ve also tried using `validates :comments, presence: true` in the `Post` model, but that led to a different behavior where it said `"Comments is invalid"` even when other fields were valid. Is there a way to make sure that if any of the nested comments are invalid, the post itself fails to save, while still displaying the right behavior messages? Any help would be appreciated! This is part of a larger service I'm building. Any help would be greatly appreciated! I've been using Ruby for about a year now. Is there a better approach? This is for a desktop app running on CentOS. Hoping someone can shed some light on this. This is for a CLI tool running on Ubuntu 22.04. I'm working with Ruby in a Docker container on Windows 10.