CodexBloom - Programming Q&A Platform

Rails 7: implementing custom validation scenarios on a conditionally required field in a nested form

👀 Views: 36 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-05
ruby-on-rails activerecord nested-forms ruby

I can't seem to get I'm stuck on something that should probably be simple... I'm prototyping a solution and I'm a bit lost with I'm trying to configure I'm working on a personal project and I'm working on a Rails 7 application where I have a nested form for creating `Order` and associated `LineItem` records... I have a custom validation on the `LineItem` model that makes the `price` field required only if a certain condition related to `product_id` is met. However, I'm running into issues where the validation does not seem to trigger as expected, leading to unexpected behavior. Here's the relevant code for my `LineItem` model: ```ruby class LineItem < ApplicationRecord belongs_to :order validates :product_id, presence: true validate :price_required_if_product_present private def price_required_if_product_present if product_id.present? && price.blank? errors.add(:price, 'must be present if product is selected') end end end ``` In the form, I'm using `accepts_nested_attributes_for :line_items` in the `Order` model: ```ruby class Order < ApplicationRecord has_many :line_items accepts_nested_attributes_for :line_items, reject_if: :all_blank end ``` When I submit the form with a `product_id` but leave `price` blank, I expect to see the validation behavior for `price`. Instead, I'm seeing a generic "Line items is invalid" behavior without any specific details. I confirmed that the `product_id` is indeed present, and I have debugged the validation method, finding that it never triggers due to the way Rails processes nested attributes. I tried moving the validation logic to the `Order` model to see if that would help, but the same scenario continues. I've also ensured that the nested attributes are being built correctly in the controller: ```ruby def new @order = Order.new @order.line_items.build end ``` Has anyone faced a similar scenario with nested forms and validations in Rails? How can I properly enforce this conditional validation on the `LineItem` model? Any insights or solutions would be greatly appreciated! This is part of a larger API I'm building. What am I doing wrong? I'm working with Ruby in a Docker container on Windows 11. Any advice would be much appreciated. Any ideas how to fix this? The project is a microservice built with Ruby. Any ideas how to fix this? I'm working on a CLI tool that needs to handle this. Any feedback is welcome!