I see 2 things that might help you. On one hand you could use
accepts_nested_attributes_for in your person model and fields_for in
your view, then you would only need to save the person and that would
take care of the client as well but based on what I see in your code
that might not be feasible. On the other hand you could wrap the code
for your save commands in a transaction and if there is any type of
error during any of the saves Rails will roll back the transaction and
you're golden.


On Dec 22, 8:30 pm, giorgio <george.pever...@gmail.com> wrote:
> I hav page where I am saving a "client" record and a "person" record.
> Sometimes the "person" is an existing record and sometimes it is a new
> record. The "client" is always new.
> Here is some code:
>
> class Person < ActiveRecord::Base
>   has_many :clients
> ....
>
> class Client < ActiveRecord::Base
>   belongs_to :person
>   validates_presence_of :person_id
>
> ....
>
>   def create
>     @client = Client.new(params[:client])
>     begin #check if the person already exists
>       @person=Person.find(params[:person][:id])
>     rescue #otherwise create new person
>       @person=Person.new(params[:person])
>     end
>     @client.pers...@person
>      begin
>       Client.transaction do
>         @person.save!
>         @client.pers...@person
>         @client.save!
>         flash[:notice] = 'Client was successfully created.'
>         redirect_to :action => 'edit', :id => @client.id
>       end
>     rescue
>       render :action => 'new'
>     end
>   end
>
> Im not really sure what the best way and order to do the saves is.
> If I try to save client first then it wont have a person_id yet and
> will fail validation.
> If I save the person first and then the client fails validation for
> some other reason the code sort of works in that it rolls back but the
> @person record has an id set even though the save failed. It also
> appears to return false for @person.new_record?
>
> Is there a tidier way to do this? I have tried @client.person.save and
> various other combinations but it is not really clear what actually
> gets saved.
>
> Any comments appreciated.
>
> George

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to rubyonrails-t...@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to