Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3: redirect_to with :remote => true

I have a delete link that makes a remote call:

<%= link_to image_tag("trash.png"), [current_user, bookcase], method:  :delete, :remote => true, confirm: "You sure?", title:   bookcase.image %>

In my controller, I end the delete function with a redirect:

def destroy
  @bookcase.destroy
  redirect_to current_user
end

This works, except it's redirecting the user to the 'user/show.html.erb' file instead of the 'user/show.js.erb' file. How can I redirect the user, specifying which format to use?

like image 202
nullnullnull Avatar asked Oct 30 '12 20:10

nullnullnull


People also ask

What does remote true do in Rails?

remote: true is really just telling the browser to not refresh the page. Do the action that you would normally do, but don't do anything to the page.

What is redirect_to in Ruby?

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.

What does redirect_to return?

redirect_to will cause any automatic rendering to be skipped. You only need the 'return' if you need to bypass further code in the action. If the further code does an explicit render , then you must do a return to avoid an error of redirect and render both being present.


2 Answers

Don't know if this is answering this specific question, but some might find the following helpful:

module AjaxHelper
  def ajax_redirect_to(redirect_uri)
    { js: "window.location.replace('#{redirect_uri}');" }
  end
end

class SomeController < ApplicationController
  include AjaxHelper

  def some_action
    respond_to do |format|
      format.js { render ajax_redirect_to(some_path) }
    end
  end
end
like image 55
Louis Sayers Avatar answered Oct 04 '22 23:10

Louis Sayers


I'm pretty sure you can specify the format in the redirect_to like this

redirect_to current_user, format: 'js'

like image 38
Leo Correa Avatar answered Oct 05 '22 00:10

Leo Correa