Ruby on rails 3 轨道3在救援区渲染

Ruby on rails 3 轨道3在救援区渲染,ruby-on-rails-3,exception-handling,transactions,Ruby On Rails 3,Exception Handling,Transactions,我正在使用事务和异常处理动态创建一系列对象。现在它按预期处理回滚和所有操作,但我的rescue块不会尝试渲染我告诉它的操作 这是我处理事务的代码 def post_validation ActiveRecord::Base.transaction do begin params[:users].each do |user| #process each user and save here end redirect_to

我正在使用事务和异常处理动态创建一系列对象。现在它按预期处理回滚和所有操作,但我的rescue块不会尝试渲染我告诉它的操作

这是我处理事务的代码

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
失败时的预期结果:回滚事务并呈现操作“验证”


失败时发生的情况:回滚事务并尝试呈现不存在的“后验证”视图。

我提供的代码似乎有一些问题。对于初学者来说,您不需要使用
raiseactiverecord::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