Skip to content

Instantly share code, notes, and snippets.

@jzellman
Created April 23, 2009 14:54
Show Gist options
  • Save jzellman/100526 to your computer and use it in GitHub Desktop.
Save jzellman/100526 to your computer and use it in GitHub Desktop.
# Wrong!
# If foo is valid but bar is not, foo is still saved.
# This breaks the transactional nature
#
def create
Foo.transaction do
@foo = Foo.create(params[:foo])
@bar = Bar.create(params[:bar])
if @foo.save and @bar.save
redirect_to some_url
else
render :action => "new"
end
end
end
# Right
# Notice how the rescue is outside the transaction.
# This causes the transaction to be rolled back
#
def create
Foo.transaction do
@foo = Foo.create(params[:foo])
@bar = Bar.create(params[:bar])
@foo.save! and @bar.save!
redirect_to some_url
end
rescue ActiveRecord::RecordInvalid => e
render :action => "new"
end
# Also works
# be careful though since the transaction is not rolled back,
# but the records are never saved
#
def create
Foo.transaction do
@foo = Foo.create(params[:foo])
@bar = Bar.create(params[:bar])
if @foo.valid? and @bar.valid?
@foo.save! and @bar.save!
redirect_to some_url
else
render :action => "new"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment