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?
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.
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.
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.
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
I'm pretty sure you can specify the format in the redirect_to like this
redirect_to current_user, format: 'js'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With