LOCKLOCK LOCKLOCK - 3 months ago 19
jQuery Question

Double Render error with rails and ajax call

I am trying to render different stuff with html and js calls. I will handle json result in ajax call.

I kept getting double rendering error saying I cannot use render and re-direct at the same time. But they are for different calls so it should not matter?

I tried to search for an answer and could not find one.

Thanks.

Below is my code:

def create
service = ServiceCall.new.call
if this
if abc
set_flash('success')
else
set_flash('notice')
end

respond_to do |format|
format.html { redirect_to(log_in_path) && return}
end
elsif that
respond_to do |format|
format.html { redirect_to(root_path) && return}
end
end

respond_to do |format|
format.js { render json: service, status: :ok }
end
end

Answer

return does not work like you expect. Your block is not executed within the current method. It is used as a parameter deeper down the chain. So you don't leave the current method. You have to change your method. One possible solution:

def create
  service = ServiceCall.new.call
  redirect_path = if this
        if abc
          set_flash('success')
        else
          set_flash('notice')
        end

        log_in_path

      elsif that
         root_path
      end

  respond_to do |format|
    format.html { redirect_to(redirect_path) }
    format.js { render json: service, status: :ok }
  end
end
Comments