Jim N.'s walkthru (http://jimneath.org/2008/09/06/multi-model-forms- validations-in-ruby-on-rails/) talks about validating multiple objects before saving. His example is below: if @person.valid? & @cat.valid? & @dog.valid? Person.transaction do @person.save! @cat.save! @dog.save! end else FAIL end I am trying to do something similar but in my situation there may not always be a @cat or @dog (there will always be a @person though). Does anyone know of a way that I can run the same validation but allow for the conditional presence of the 2 objects? Thanks.
on 2009-04-07 13:27
on 2009-04-08 09:04
Hmmm.. Are Cat and Dog associated to the Person model? > there may not always be a @cat or @dog Meaning the parameters for these models will be passed in from the form but they will be empty? In which case you can have a before_validation callback and check if all the params for these models are blank. If they are, then return false. This will still throw a "Cat/Dog is invalid" validation error. That can be handled by hacking into error_messages_for. Its all quite ugly but it works. I can tell you more if you can explain the context better.
on 2009-04-08 09:19
Sure. My scenario is a bit different. I have an application form that needs to be filled in by a user. If the user is not registered on my site I have a few fields that allow the user to quickly enter name and email and their account will be created when the application is submitted. At the same time, the application allows a user to pick from a list of documents they've uploaded. However, I also have fields incase a user would like to upload a document that is not on the list (to save them the hassle of going back, uploading and returning to the application). Therefore, my application will always have a new @application and sometimes a new @user or @document. The document model is polymorphic. The application belongs_to the user and has a field for document_id but I did not create an explicit relationship in the model. Thanks for any help.
on 2009-04-08 15:16
Just wanted to say that someone helped me with the solution here: http://railsforum.com/viewtopic.php?id=29103 Apparently, it's as simple as: def valid_or_nil?( model ) model.nil? ? true : model.valid? end if @person.valid? & valid_or_nil?(@cat) & valid_or_nil?(@dog) Person.transaction do @person.save! @cat.save! unless @cat.nil? @dog.save! unless @dog.nil? end else FAIL end