ruby-on-rails - 有没有办法重新渲染?

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

我编写了一个 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 时,它会引发双重渲染异常,因为渲染已在 Controller 中调用。

有没有办法覆盖/取消初始渲染调用?

ruby 2.1.8

rails 4.2.6

最佳答案

尝试在操作本身中添加救援 block 。

 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 即可呈现显示页面。

关于ruby-on-rails - 有没有办法重新渲染?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36546937/

相关文章:

javascript - 在 Rails 的一个 View 页面中使用多个表单时出现冲突吗?

ruby-on-rails - unicorn 中每个 worker 的最大请求数

ruby-on-rails - 在 Rails/Sinatra 中为 iphone 重定向

ruby-on-rails - 如何在一些数据之后进行迭代?

ruby - 在迁移中从 lambda 指定默认值

javascript - Rails 4 ajax 更新 div

ruby-on-rails - Git 或 SVN for Rails 应用程序?

ruby-on-rails - 使用从另一个站点抓取的内容填充 Rails 应用程序

ruby-on-rails - 警告 : Can't mass-assign protected attributes Paperclip Rails 4

ruby-on-rails - rails 4 x paper_trail : filter versions by item_id with nested resources