Stef T
2006-Aug-07 14:57 UTC
[Rails] Capturing Validation Errors from Nested Model Creation..
Hello Everyone, The subject sort of says it all ;) but, I will explain. Currently I have an object (Booking) which, when its created, will also have new contacts created everytime with it (for arguements sake). So, I can wrap these both in a transaction, however, if any one of the contacts fails the validation of the contact model, it will fling up a validation error. So, what is the best way to capture this error and return it to the page for display ? I thought of trying Booking.transaction do @allerrors = [] contact = Contact.new(:first_name => params["contact"]["first_name"]) if not contact.valid?() then contact.errors.each {|attr| @allerrors.push(attr) } end # other stuff goes here if @allerrors.empty? and @booking.save then @booking.contact = myContacts flash[:notice] = ''Booking was successfully created.'' redirect_to :action => ''list'' else @booking.errors.each {|attr| @allerrors.push(attr) } redirect_to :action => ''new'', :errors => @allerrors end end This is a rather contrived example, but I hope you get the idea :) I could check the booking''s validation to make sure it always has at least one contact, however, that would not help in the case of a booking where 3 out of the 4 contacts validated ''fine''. I would like to use the generic error routines if possible (you know, red box on page view, etc etc) but how ? Regards Stef