Ruby 在 Rails - AbstractController::DoubleRenderError

Ruby on Rails - AbstractController::DoubleRenderError

我尝试在我的创建方法中添加一个重定向到我的支持票。但我总是得到

AbstractController::DoubleRenderError

但是我在上传文件后需要这个重定向。我怎样才能解决这个问题 ?

上传控制器:

def create

   @upload = Upload.new(params[:upload])

      respond_to do |format|
          if @upload.save
           format.html {
             render :json => [@upload.to_jq_upload].to_json,
             :content_type => 'text/html',
             :layout => false
           }

           format.json { render json: {files: [@upload.to_jq_upload]}, status: :created, location: @upload }

        else
           format.html { render action: "new" }
           format.json { render json: @upload.errors, status: :unprocessable_entity }
        end
        redirect_to new_support_ticket_path
     end
end

upload.rb :

class Upload < ActiveRecord::Base
  attr_accessible :upload
  has_attached_file :upload

  include Rails.application.routes.url_helpers

  def to_jq_upload
    {
      "name" => read_attribute(:upload_file_name),
      "size" => read_attribute(:upload_file_size),
      "url" => upload.url(:original),
      "delete_url" => upload_path(self),
      "delete_type" => "DELETE" 
    }

  end

end

renderredirect 都没有停止控制器动作的执行。而且您不能在同一操作中同时使用 renderredirect。这就是错误所说的。由于您已经在渲染视图,因此请删除控制器操作末尾的 redirect

def create

 @upload = Upload.new(params[:upload])

  respond_to do |format|
      if @upload.save
       format.html {
         render :json => [@upload.to_jq_upload].to_json,
         :content_type => 'text/html',
         :layout => false
       }

       format.json { render json: {files: [@upload.to_jq_upload]}, status: :created, location: @upload }

    else
       format.html { render action: "new" }
       format.json { render json: @upload.errors, status: :unprocessable_entity }
    end
 end
end

有关更多信息,请在 http://guides.rubyonrails.org/layouts_and_rendering.html#using-render

中搜索 避免双重渲染错误

因为它不允许您在 render 之后 redirect_to。我认为 redirect_to new_support_ticket_path 应该放在 format.html 块中,因为你需要 redirect_to 在 html 视图中。

@upload = Upload.new(参数[:upload])

  respond_to do |format|
      if @upload.save
       format.html {
         redirect_to new_support_ticket_path
       }

       format.json { render json: {files: [@upload.to_jq_upload]}, status: :created, location: @upload }

    else
       format.html { render action: "new" }
       format.json { render json: @upload.errors, status: :unprocessable_entity }
    end
 end

结束

尝试在重定向后使用 return 命令