Forum: Ruby on Rails Multi Model Forms and Validations

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
sshefer (Guest)
on 2009-04-07 13:27
(Received via mailing list)
Jim N.'s walkthru (
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!!!

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?

Ram (Guest)
on 2009-04-08 09:04
(Received via mailing list)
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.
sshefer (Guest)
on 2009-04-08 09:19
(Received via mailing list)

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.
sshefer (Guest)
on 2009-04-08 15:16
(Received via mailing list)
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)
  Person.transaction do!! unless @cat.nil?! unless @dog.nil?
Julian L. (Guest)
on 2009-04-09 02:36
(Received via mailing list)

What's wrong with

def valid_or_nil?(obj)
obj.nil? or obj.valid?

Learn rails:
This topic is locked and can not be replied to.