在Rails ActiveRecord上忽略异常保存

时间:2016-06-03 21:30:54

标签: ruby-on-rails ruby activerecord

如果引发异常,我试图不在数据库中保存记录但由于某种原因它被忽略。记录保存无论如何。我究竟做错了什么?任何帮助表示赞赏。谢谢!

#这是我的控制器
    # POST /users
      def create
        service_action(success: @support_user, fail: :new) do |service|
          service.create_user
        end
      end

    def service_action(page)
        result = yield(SupportUserService.new(@support_user, App.logger))
        if result[:ok]
          redirect_to page[:success], :notice => result[:message]
        else
          flash[:error] = result[:message] if result[:message].present?
          render page[:fail]
        end
      end
#这是服务类 - > SupportUserService
    def create_user
      return_hash(:create) do |h|
        if user.save
          grant_ssh_access(user.login, user_ssh_keys!)
          h[:ok] = true
          h[:message] = "Support User '#{user.login}' was successfully created."
        end
      end
    end


    def return_hash(action)
      {ok: false, message: ''}.tap do |h|
        begin
          yield h
        rescue => e
          h[:ok] = false
          h[:e] = e
          h[:message] = "Failed to #{action} support user: #{e.message}"
          logger.error(stacktrace("Failed to #{action} support user", e))
        end
      end
    end

2 个答案:

答案 0 :(得分:1)

#save替换为异常提升版#save!,并删除if子句,以便获得:

return_hash(:create) do |h|
   user.save!
   grant_ssh_access(user.login, user_ssh_keys!)
   h[:ok] = true
   h[:message] = "Support User '#{user.login}' was successfully created."
end

这将在保存失败时引发异常,您将能够将其捕获到#return_hash

答案 1 :(得分:0)

我通过在user.save方法之外移动grant_ssh_access函数来修复此问题。这样,如果该函数返回异常,它将在到达save方法之前被捕获并退出。