Redirect does not work

I have this line in the voice controller:

before_filter :authenticate 

Therefore, when I vote upon exiting the system, it should disable this filter.

My authentication method in my application controller is as follows:

 def authenticate logged_in? ? true : access_denied end 

So, it returns access_denied , which looks like this:

 def access_denied redirect_to login_path, :notice => "You must log in to perform this action." and return false end 

So I have to be redirected to my login page, right?

I have this in the routes.rb file:

 match '/login' => "sessions#new", :as => "login" 

and I have a new view with a login form, which I should be redirected to when I vote and I have not logged in. I also have this code in the create method of my voice controller:

 if @vote.save respond_to do |format| format.html { redirect_to @video } format.js end else respond_to do |format| format.html end end 

But when I vote, I am not redirected, and I get this error message in my logs:

 Started GET "/login" for 127.0.0.1 at Thu Mar 24 21:18:08 -0700 2011 Processing by SessionsController#new as JS Completed in 17ms ActionView::MissingTemplate (Missing template sessions/new with {:locale=>[:en, :en], :formats=>[:js, "*/*"], :handlers=>[:rhtml, :rxml, :erb, :builder, :rjs]} in view paths "/rubyprograms/dreamstill/app/views"): 

Why is this happening, and how can I make this redirect work?

+4
source share
2 answers

It seems you are making a javascript request to your VotesController # create action, but you are missing the JS template for # new sessions.

Here's what happens: you call VotesController # create as a JS call, and when the user logs into everything, everything is fine, because VotesController # creates a response to javascript actions. The problem is that if the user is not logged in, the request is redirected to SessionController # new, and the request is still a javascript request. The problem is that SessionController # new is not responding to JS, so you get the missing template error.

I would recommend adding the app / views / sessions / new.js.erb file to handle the JS call. You probably only have the app / views / sessions / new.html.erb file.

You can also handle this case by redirecting using javascript to an HTML request. You can do this by adding the following to your new.js.erb template:

 window.location = "<%= escape_javascript(login_path) %>"; 

This basically tells the browser to redirect to login_path, as if the request was an HTML request instead of a Javascript request.

+6
source

Since the request causing the problems is ajax, try adding a check to your before_filter file to see if the request is js.

 if request.xhr? render :text => "document.location = '#{login_path}';", :layout => false else redirect_to login_path, ... end 
+1
source

Source: https://habr.com/ru/post/1345180/


All Articles