Creating two activerecords with one form

There must be a better way of doing this.

If website.save fails…I’m stuck with the new domain, thats not
associated to a website.

def create
website = Website.new(params[:website])
website.domain = Domain.create(params[:domain])
if website.save
:flash[:notice] = Server.create_website website
redirect_to :action => ‘list’
else
render :action => ‘new’
end
end

On 2007-10-31 09:40:20 -0700, “Chris.Mohr”
[email protected] said:

There must be a better way of doing this.

If website.save fails…I’m stuck with the new domain, thats not
associated to a website.

This is a good tutorial on the subject:

…also check out parts 2 and 3 of this lesson.

–Andrew

For that you need to use transaction method so that if one save fails
due to any reason then whole transaction should roll back. Something
like this:

def create
website = Website.new(params[:website])
website.domain = Domain.create(params[:domain])
begin
Website.transaction do
# the ! in save method is needed to raise any exceptions
website.save!
website.domain.save!
end
:flash[:notice] = Server.create_website website
redirect_to :action => ‘list’
rescue
flash[:notice] = “Your error message”
render :action => ‘new’
end
end

Hope that helps…

Also check www.sphred.com