Topic: Newbie: Mulitple Model Validation Question

I am a newbie to Rails so I apologize if this question has been answered, but I have no found it in the forums.

So I have an object model like this:

Contact << Address (A Contact can have many addresses).
Contact < Picture (A Contact can have picture).

For now I am only using the first address of the model, but I wanted to be able to expand that to multiple addresses without doing much rework.

Right now my update method for a contact looks like the following:

[code=Update Method]
    @contact = Contact.find(params[:id])
    logger.debug("#{self}: Updating Contact-> #{@contact.name}, #{@contact.id}")
    @contact.update_attributes(params[:contact])
    @picture = @contact.picture
    @picture == nil ? @picture = @contact.build_picture(params[:picture]) : @picture.update_attributes(params[:picture])
    @contact.addresses.first == nil ? @contact.addresses << Address.new(params[:address]) : @contact.addresses.first.update_attributes(params[:address])
    if @contact.valid? && @picture.valid? && @contact.addresses.first.valid?
      if @contact.save
        @contact.addresses.first.save
        @picture.save
      end
      flash[:notice] = 'Contact was successfully created.'
      redirect_to :action => 'show', :id=>@contact.id
    else
      @combinedErrors = @contact.errors.full_messages + @picture.errors.full_messages
      render :action => 'edit'
    end
[/code]

2 Questions:

1.  Is there an easier more rails way of doing the validation part.  To me that looks like a clumsy way to valid all three models.

2.  When trying to validate the picture object is there any way to use conditional logic... for example something like this:

[code=Sample Validation]
validates_format_of :content_type, :with => /^image/, :message => "you can only upload images"
unless :content_type.blank?
[/code]


Thanks

Re: Newbie: Mulitple Model Validation Question

I found the answer, use the validates_associated to check the validation's for a sub model.  Then to show them make sure to reference the sub model's errors.full_messages method.  That will allow you to get to the bottom of the error stack. 

[code=Contact Model]
  validates_associated :picture
  validates_associated :addresses
[/code]

And the new update method

[code=Update Method]
    @contact = Contact.find(params[:id])
    @contact.update_attributes(params[:contact])
    @contact.picture == nil ? @contact.build_picture(params[:picture]) : @contact.picture.update_attributes(params[:picture])
    @contact.addresses.first == nil ? @contact.addresses << Address.new(params[:address]) : @contact.addresses.first.update_attributes(params[:address])
    if @contact.save
      flash[:notice] = 'Contact was successfully created.'
      redirect_to :action => 'show', :id=>@contact.id
    else
      @combinedErrors = @contact.errors.full_messages + @contact.picture.errors.full_messages
      render :action => 'edit'
    end
[/code]