Javascript redirect_to in rails
I'm developing a Facebook application in Rails. Some (not all) of the pages require the user to be logged in; if not, they are redirected to a "login" page. I can't use redirect_to
for 开发者_运维知识库this, as the redirect needs to be done via Javascript (as it's redirecting the parent frame); furthermore, the redirection needs to know the address of the originally requested page (to come back to), so I can't just redirect to a dummy page that will do the redirection.
I've tried using a layout together with render
to achieve this, however the original view is still run (though not yielded); since the view requires variables that only exist when the user is logged in, this creates errors, crashing the script.
Is it possible to render the layout but stop the view from executing? Is there a better way to accomplish this?
Could you put your logic in a method called by before_filter in application_controller and check whether redirection is needed? Something like:
class ApplicationController < ActionController::Base
before_filter :authenticate_user!
def authenticate_user!
if (authentication_required? && !user_authenticated?)
render :js => "[some javascript here]" and return
end
end
def authentication_required?
# logic to determine if auth is needed
end
def user_authenticated?
# logic to determine if user is authenticated
end
end
The render :js => ... should let you render JavaScript with whatever values you need to return to the originally requested page (or you can render some other file or arbitrary text).
精彩评论