Jim Neath'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?
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?
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.
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
Thanks for any help.
Just wanted to say that someone helped me with the solution here:
Apparently, it's as simple as:
def valid_or_nil?( model )
model.nil? ? true : model.valid?
if @person.valid? & valid_or_nil?(@cat) & valid_or_nil?(@dog)
@cat.save! unless @cat.nil?
@dog.save! unless @dog.nil?
What's wrong with
obj.nil? or obj.valid?
Learn rails: http://sensei.zenunit.com/