我正在使用事务和异常处理动态创建一系列对象。现在它处理回滚和所有预期的但我的救援块不会尝试渲染我告诉它的动作。
这是我处理交易的代码
def post_validation
ActiveRecord::Base.transaction do
begin
params[:users].each do |user|
#process each user and save here
end
redirect_to root_path #success
rescue ActiveRecord::RecordInvalid
# something went wrong, roll back
raise ActiveRecord::Rollback
flash[:error] = "Please resolve any validation errors and re-submit"
render :action => "validation"
end
end
end
失败时的预期结果:回滚交易并呈现“验证”操作。
失败后会发生什么:回滚交易并尝试呈现不存在的“post_validation”视图。
答案 0 :(得分:2)
看起来我提供的代码存在一些问题。对于初学者,您不需要打扰raise ActiveRecord::Rollback
行,当事务块内部抛出异常时,Rails会在幕后执行此操作。此外,事务块需要位于begin块内。结果代码看起来像这样:
def post_validation
begin
ActiveRecord::Base.transaction do
#process some new records here
redirect_to root_path
end
rescue ActiveRecord::RecordInvalid
# handle the exception here; the entire transaction gets rolled-back
flash[:error] = "Please resolve any validation errors and re-submit"
render :action => "validation"
end
end