如何在ruby轨道上保存模型后回滚?

时间:2014-07-24 09:49:06

标签: ruby-on-rails ruby-on-rails-3.2

我在rails 3.2上使用ruby这段代码

def craete
  @account = Account.new(account_params)
    if @account.save
      @account = Account.where(name: params[:name]).first
      @tenant = Tenant.new()
      @tenant.name = @account.name
      @tenant.account_id = @account.id          
      if !@tenant.save
        raise ApiError.new(ApiError::VALIDATION, @tenant.errors, 1103, :unprocessable_entity)
      end
      audit('Admin.Account.Create', account_params)
      @success = ApiSuccess.new(@account, 1210, request.method, false, 'Account created')
      render '/api_success', status: :created
    else
      raise ApiError.new(ApiError::VALIDATION, @account.errors, 1103, :unprocessable_entity)
    end
end

我的问题是,如果租户无法保存,我们如何才能回滚帐户?

非常感谢

1 个答案:

答案 0 :(得分:0)

为此,您需要使用transaction。在事务块下保存帐户和租户。如果其中任何一个失败,整个交易将被回滚

@account.transaction do 
  if @account.save
   @account = Account.where(name: params[:name]).first
   @tenant = Tenant.new()
   @tenant.name = @account.name
   @tenant.account_id = @account.id          
   if !@tenant.save
     raise ApiError.new(ApiError::VALIDATION, @tenant.errors, 1103, :unprocessable_entity)
   end
   audit('Admin.Account.Create', account_params)
   success = ApiSuccess.new(@account, 1210, request.method, false, 'Account created')
   render '/api_success', status: :created
 else
  raise ApiError.new(ApiError::VALIDATION, @account.errors, 1103, :unprocessable_entity)
 end