Aarthi
Aarthi

Reputation: 1521

Rails redirect to index page after delete

I need to place delete link at the show page of the object. This show page is to rendered at two different controllers. In which I need to redirect to the index page from which the request came from. The URL would be
localhost:3000/users (index page) which will have link to books (show page) that URL will be local host:3000/books/I'd. And at another controller index page local host:3000/books and that too have link to books show page which have delete link in it. I need to redirect to the index page from which the request came from. Any help

Edit: How to redirect to previous page in Ruby On Rails? (Question already there) We can get the request URL at edit action. But here the delete action will be at common show page

Upvotes: 0

Views: 1950

Answers (3)

dimpiax
dimpiax

Reputation: 12687

ruby 2.5.1p57 | Rails 5.2.0

Put at the end of your method:

redirect_to action: :index

Upvotes: 0

max
max

Reputation: 102222

You could track the visit to the index pages by storing it in the session:

class ApplicationController
  private 
  def store_location
    session[:stored_location] = request.path
  end

  def stored_location
    session[:stored_location]
  end
end

class UsersController
  before_acton :store_location, only: [:index]
  # ...
end

class BooksController
  before_acton :store_location, only: [:index]
  # ...
end

You can this just use it your destroy action:

class BooksController
  def destroy
    @book.destroy
    redirect_to stored_location || books_path
  end
end

Upvotes: 3

Yechiel K
Yechiel K

Reputation: 538

If I understood your question correctly, you can put the following in your delete controller:

redirect_to :back

that should redirect back to the page the user came from.

Upvotes: 0

Related Questions