Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double render error rails

Not sure how its possible to get this error :

AbstractController::DoubleRenderError users#create

When in my controller I got this code :

render 'new' and return

I got the log from the bugsnag saying that I got the error at this line.

This is the create method code :

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

I have before filter in this controller :

before_filter :signed_in_user

def signed_in_user
      unless signed_in?
        store_location
        redirect_to signin_url, notice: "Please sign in."
      end
    end
like image 809
Gandalf StormCrow Avatar asked Feb 06 '14 17:02

Gandalf StormCrow


People also ask

What is a double render?

Usually double render errors are caused because you have a code path that conditionally sends some response and then have more code after it intended to handle other conditions, but you failed to add a return statement after conditionally responding.

Does redirect_to return?

redirect_to is not return Keep in mind that redirect_to does not cause the action to stop executing. It is not like calling return in a Ruby method.

How do I redirect in rails?

Rails's redirect_to takes two parameters, option and response_status (optional). It redirects the browser to the target specified in options. This parameter can be: Hash - The URL will be generated by calling url_for with the options.


2 Answers

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 ....

like image 99
Thomas Klemm Avatar answered Sep 19 '22 14:09

Thomas Klemm


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

like image 22
cbrulak Avatar answered Sep 20 '22 14:09

cbrulak