Redirect not working

前端 未结 2 1816
难免孤独
难免孤独 2021-01-19 21:13

I have this line in my votes controller:

before_filter :authenticate

So when I vote while logged out, it should fail this filter.

M

相关标签:
2条回答
  • 2021-01-19 21:57

    Since the request that is causing problems is ajax try adding a check within your before_filter to whether the request is js.

    if request.xhr?
        render :text => "document.location = '#{login_path}';", :layout => false
    else
      redirect_to login_path, ...
    end
    
    0 讨论(0)
  • 2021-01-19 22:07

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

    Here's what happens: you make a call to VotesController#create as a JS call, and when the user is logged in all is fine, because VotesController#create response to javascript actions. The problem is that if the user is not logged in, the request redirects to SessionsController#new, and the request is still a javascript request. The problem is that SessionsController#new does not respond to JS so you get a missing template error.

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

    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 will basically tell the browser to redirect to the login_path as if the request were an HTML request, instead of a Javascript request.

    0 讨论(0)
提交回复
热议问题