LOCKLOCK
LOCKLOCK

Reputation: 351

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

Upvotes: 0

Views: 486

Answers (1)

slowjack2k
slowjack2k

Reputation: 2586

Maybe return does not work like you expect and 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. 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

Upvotes: 1

Related Questions