Validate 2 models in 1 form?

I have 2 models, an artist and song model

I have the validates_presence_of on each of the models (for checking title, artist name, and etc). They validate fine when you add items on their own controller (1 form for each model),

but my program doesn't validate when I combine both models in 1 form.

1. Maybe There's no attribute in one of your model, you can use attr_accessor. 2. Have you tried like this ?

are artists and songs related? (I assume they are). If so, how? How are you creating each model in your one form? You may want something similar to the following:

class Artist < AR::Base   has_many :songs   validates_presence_of :name end

class Song < AR::Base   belongs_to :artist   validates_presence_of :title end

class SomeController < ActionController   def new     @artist = Artist.new     @song = @artist.songs.build   end

  def create     @artist = Artist.new(params[:artist])

    # append a new song to the list of songs for the artist     # you may want to loop through a collection of songs passed from the form     # if you want to provide the ability to add multiple songs at once, or you could build     # this into the model     @song = @artist.songs.build(params[:songs])

   if @artist.save      # both the artist and its related song objects are valid    else      # either artist was invalid or the song object was    end   end end

and in your view:

views/artists/new.html.erb

<%= error_messages_for :artist, :song %>

Of course the above gets more complicated if you want to assign multiple songs at a time, but this should at least get you started.

Mike

Yow... Mike, YOurs is more reasonable than me.

Feng Tien wrote:

I have 2 models, an artist and song model

I have the validates_presence_of on each of the models (for checking title, artist name, and etc). They validate fine when you add items on their own controller (1 form for each model),

but my program doesn't validate when I combine both models in 1 form.

Use

validates_associated :song # in artist model

validates_associated :artist # in song model

http://ar.rubyonrails.com/classes/ActiveRecord/Validations/ClassMethods.html#M000304

Stephan

Stephan,

Please note in the API:

I see, then can add a field like this

class Artist < ActiveRecord::Base

  :attr_accessor skip_validate_song   validates_associated :song, :if => Proc.new { |record| !record.skip_validate_song }

end

(and / or equivalent to Song class)

Plus set that in the controller as the case may be.

Stephan