简体   繁体   中英

Rails redirect to previous page (back) after delete

Is there a way to include a redirect in a link_to? I want to just refresh the current page after a delete. But, you can delete the same record from multiple views in the app.

This is the link_to:

<%= link_to 'Delete', expense, confirm: 'Are you sure?', method: :delete, :class => 'btn btn-mini btn-danger' %>

If not, does it make sense to save the current_url in flash[:fromurl] then put that in the Controller destroy section like this:

   respond_to do |format|
     format.html { redirect_to flash[:fromurl] }
     format.json { head :no_content }
   end

Thanks for the help!

You can use the redirect_to :back :

respond_to do |format|
  format.html { redirect_to :back }
  format.json { head :no_content }
end

It uses the header "HTTP_REFERER" from the request:

redirect_to :back
# is a shorthand for:
redirect_to request.env["HTTP_REFERER"]

In Rails 5 ( Official Docs ) you can use the updated: redirect_back(fallback_location: root_path)

Using this redirects the user to the referring page (previous page, the same as redirect_to :back ). If this isn't possible, it then redirects to a fallback location specified in the controller.

An example of a method in your controller (this redirects the user to the root path as a fallback location):

def some_method
    #Your Code Here
    redirect_back(fallback_location: root_path)
end

An example of a method for deleting an expense and redirecting back, with a fallback to the root_path :

def destroy
    @expense.destroy
    redirect_back(fallback_location: root_path)
end

Below are some other examples of the fallback_location 's that can be used to redirect the browser back to a specific page, if the referring page cannot be redirected to:

redirect_back fallback_location: "http://www.google.com"      #Redirects to Google (or any website you specify)
redirect_back fallback_location:  "/images/screenshot.jpg"    #Redirects to a local image
redirect_back fallback_location:  posts_path                  #Redirects to the 'posts' path
redirect_back fallback_location:  new_user_path               #Redirects to the new user path 

你也可以试试这个。

render :nothing => true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM