Ruby on Rails Thursday, December 23, 2010

Thanks for reply pepe.
You say to use a transaction... I already am using a transaction!

The issue is that if the person save succeeds and the client save
fails then the transaction is rolled back fine. However the person
record now has a person.id and subsequent code assumes that the record
is saved and tries to refind the record which of course does not
exist.

I have got around this by saving the original value of the person.id
and then resetting it in the rescue clause but it is a bit messy.

One other issue is that the only validation errors that get set are
the errors from the first record (person) that is saved so the user
may fix these up only to find new validation errors from the second
record...

I'm sure there must be a tidy way!

My latest version which works but is not pretty is:

def create
begin #try to find existing person
@person=Person.find(params[:person][:id])
rescue #they dont exist so create new
@person=Person.new(params[:person])
end
person_id=@person.id

@client=Client.new(params[:client])
begin
Person.transaction do
@person.save!
@client.person=@person
@client.save!
flash[:notice] = 'Client was successfully created.'
redirect_to :action => 'edit', :id => @client.id
end
rescue
#reset client and person to param values
@person.id=person_id
render :action => 'new'
end
end

Cheers
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-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

No comments:

Post a Comment