Nested Attributes Failing Validation Silently

I love the May of WTFs idea, thanks for your open-mindedness in hearing the community. Raising bug reports when not sure of default Rails behaviour can be daunting.

I have experienced situations where an attempt to save an ActiveRecord model, say Invoice, will return neither true nor false because it accepts accepts_nested_attributes_for :invoice_line_items and the instance of InvoiceLineItem does not pass validation.

Aspects of this I can understand but I’m not sure whether this is expected behaviour and, if so, I think it should be better documented. Particularly when I use something such as @invoice.save! I would expect the record to save or an error to be thrown.

2 Likes

Hi. I was also having the same case, but then I found validates_associated, which would make sure to check if the association is valid. Like this:

# Invoice.rb

validates_associated :invoice_line_items

after that, you can expect @invoice.save to work :slight_smile:

from the guide: Active Record Validations — Ruby on Rails Guides

1 Like

I wonder if there’s a way to run association validations, a la validates_associated, automatically when associations are added via nested attributes. There might be some hook for this in the autosave cycle.

1 Like

Thanks @wasifhossain!

I think that’s an excellent idea, @Betsy_Haibel. This strikes me as a ‘WTF’ because Rails does so much other stuff ‘by magic’, I think that validating nested models fits within this remit. I am surprised it doesn’t!