Created
April 23, 2009 14:54
-
-
Save jzellman/100526 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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