【问题标题】:is there a way to re-render?有没有办法重新渲染?
【发布时间】:2016-08-01 12:16:27
【问题描述】:

我已经编写了一个 API,用于从所有 StandardError 中解救出来。如果出现任何 StandardError,我会发送异常电子邮件并呈现带有错误消息的 json。

class ApplicationController < ActionController::Base
    rescue_from StandardError, with: :respond_with_error
    def respond_with_error(e)
        ExceptionNotifier.notify_exception(e)
        respond_to do |format|
            format.html { render json: {error: e.message}, status: :unprocessable_entity, content_type: 'application/json' }
            format.json { render json: {error: e.message}, status: :unprocessable_entity }
        end
    end
end

class UsersController < ApplicationController
    def create
        User.transaction do
            @user = User.new(user_params)
            authorize @user
            @user.save!
        end
        respond_to do |format|
            format.json { render :show, status: :created, location: @user }
        end
    end
end

这很有效,除非从 UserController#create 中的 render :show 引发异常。当我再次在 ApplicationController 中使用 respond_with_error 的错误消息渲染 json 时,它会引发双重渲染异常,因为渲染已经在控制器中调用。

有没有办法覆盖/关闭初始渲染调用?

红宝石 2.1.8

导轨 4.2.6

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4


    【解决方案1】:

    尝试在动作本身中添加救援块。

     def create
        User.transaction do
          @user = User.new(user_params)
          authorize @user
          @user.save!
        end
    
        flash.now[:success] = "successfully updated"
        redirect_to @user and return 
    
      rescue StandardError => e
        respond_with_error(e)
      end
    

    只需使用 redirect_to @user 来呈现显示页面。

    【讨论】:

    • 我想避免在每个控制器的每个动作中添加救援,它不会改变任何东西。关于重定向,我的 rails 应用程序是一个 API,因此客户端应用程序期望创建的对象作为响应。
    • 在这种情况下,只需渲染 :json => { status: created, user_object: @user } 并返回就足够了。
    【解决方案2】:

    不看任何代码都很难说。但通常 DoubleRenderException 可以通过 return 来避免,即

    render :json => response_hash and return
    

    【讨论】:

    • 感谢您的回复。我已经添加了代码。如您所见,我需要关闭导致异常的初始渲染,然后渲染带有错误消息的 json。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-05
    相关资源
    最近更新 更多