双重渲染错误轨道

Gan*_*row 10 ruby ruby-on-rails

不确定如何获得此错误:

AbstractController::DoubleRenderError users#create
Run Code Online (Sandbox Code Playgroud)

在我的控制器中,我得到了这个代码:

render 'new' and return
Run Code Online (Sandbox Code Playgroud)

我从bugsnag得到了日志,说我在这一行得到了错误.

这是创建方法代码:

def create
    back_button and return if params[:back_button]

    @profile = current_user.build_profile(params[:user])

    if @profile.nil? || current_user.nil? || @profile.user.nil?
      sign_out
      redirect_to signup_path and return
    end

    if @profile.new_record?
      render 'new' and return
    else
      redirect_to more_questions_path and return
    end
end
Run Code Online (Sandbox Code Playgroud)

我在此控制器中进行过滤之前:

before_filter :signed_in_user

def signed_in_user
      unless signed_in?
        store_location
        redirect_to signin_url, notice: "Please sign in."
      end
    end
Run Code Online (Sandbox Code Playgroud)

Tho*_*emm 15

尝试一下:

class UsersController < ApplicationController
  before_filter :signed_in_user

  def create
    return back_button if params[:back_button]

    @profile = current_user.build_profile(params[:user])

    if @profile.nil? || current_user.nil? || @profile.user.nil?
      sign_out
      return redirect_to signup_path
    end

    if @profile.new_record?
      render 'new'
    else
      redirect_to more_questions_path
    end
  end

  private

  def signed_in_user
    unless signed_in?
      store_location
      return redirect_to signin_url, notice: "Please sign in."
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

背后的原因:x and return意味着x and return nil,因此回归nil.实际上,您尝试将控制器动作短路,并且return redirect_to ....

  • @AdamGrant [从 Rails 控制器提前返回的 4 种方法](http://blog.arkency.com/2014/07/4-ways-to-early-return-from-a-rails-controller/) (2认同)

Coe*_*ulf 6

并且没有为你做任何事情.

在你拥有的每个地方

xxx and return
Run Code Online (Sandbox Code Playgroud)

用它替换它

xxx
return
Run Code Online (Sandbox Code Playgroud)

对于exameple:

redirect_to signup_path
return
Run Code Online (Sandbox Code Playgroud)

这应该更像你期望的那样