Ruby on Rails - AbstractController :: DoubleRenderError

时间:2016-08-29 10:06:10

标签: ruby-on-rails ruby ruby-on-rails-3

我尝试添加到我的create-method,重定向到我的支持票据。但我总是得到一个

  

一个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

3 个答案:

答案 0 :(得分:1)

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

@upload = Upload.new(params [: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

答案 1 :(得分:1)

重定向后尝试使用return命令

答案 2 :(得分:0)

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

中搜索避免双重渲染错误