Double render error rails

前端 未结 4 1574
借酒劲吻你
借酒劲吻你 2021-01-04 12:47

Not sure how its possible to get this error :

AbstractController::DoubleRenderError users#create

When in my controller I got this code :

相关标签:
4条回答
  • 2021-01-04 13:21

    Give this a try:

    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
    

    The reasoning behind it: x and return means x and return nil, thus returns nil. Actually, you try to short-circuit the controller action, and return redirect_to ....

    0 讨论(0)
  • 2021-01-04 13:28

    You have a render and a redirect. You have to pick one.

    0 讨论(0)
  • 2021-01-04 13:30

    I suppose redirect_to signup_path is returning either nil or false, thus your and return is not being executed.

    You can fix this many ways, the simplest is replace

    redirect_to signup_path and return
    

    by

    redirect_to signup_path
    return
    

    Yet, I suggest you to do a bigger change. Try changing this

    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
    

    By

    if @profile.nil? || current_user.nil? || @profile.user.nil?
      sign_out
      redirect_to signup_path
    elsif @profile.new_record?
      render 'new'
    else
      redirect_to more_questions_path
    end
    

    This way it is clear that only one path can be taken, without relying on return.

    0 讨论(0)
  • 2021-01-04 13:41

    The and isn't doing anything for you.

    In each place where you have

    xxx and return
    

    replace it with

    xxx
    return
    

    For exameple:

    redirect_to signup_path
    return
    

    That should work more like you would expect it to

    0 讨论(0)
提交回复
热议问题