Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails redirect_to :back not working

I'm trying to use the following:

class PaymentsController < ApplicationController    def addproduct      (session[:products] ||= []) << params[:item]      redirect_to :back   end   end 

I got this exception:

undefined method `back_url' for #<PaymentsController:0x007ff682c467a8> 

Why this is happening?

like image 686
Lechucico Avatar asked May 21 '17 15:05

Lechucico


People also ask

How do I redirect back in rails?

In Rails 4. x, for going back to previous page we use redirect_to :back. However sometimes we get ActionController::RedirectBackError exception when HTTP_REFERER is not present. This works well when HTTP_REFERER is present and it redirects to previous page.

What is request referer in rails?

request.referer gives you the previous URL or / if none. It is usually used to redirect the user back to the previous page (link) More information here. Regarding your question, it is simply returning 'dashboard' if found in request.referer .


2 Answers

Rails 5 has redirect_back, instead of redirect_to :back. It was changed as it used to raise an exception when request's HTTP_REFERER was not present.

So use this:

redirect_back fallback_location: root_path 

You can change root_path to something else as per your requirements.

like image 73
Surya Avatar answered Sep 23 '22 23:09

Surya


redirect_to :back was deprecated in Rails 5.0 (see PR) and then removed in Rails 5.1

Use the following instead:

redirect_back(fallback_location: root_path) 
like image 45
spickermann Avatar answered Sep 24 '22 23:09

spickermann