0

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

这是我处理交易的代码

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”。

4

1 回答 1

2

好吧,我提供的代码似乎有一些问题。对于初学者来说,您不需要担心这raise ActiveRecord::Rollback条线,当在事务块内引发异常时,Rails 会在幕后执行此操作。此外,事务块需要在开始块内。所以生成的代码看起来像这样:

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
于 2012-10-17T17:22:56.790 回答