ruby rails - 重定向到原始请求 url [英] ruby rails - redirect to original request url
问题描述
这是我重定向到默认 url(myapp_url) 的内容.但是我想更改重定向以转到用户在身份验证后输入的请求 url.我怎么做?我在这里搜索时尝试了几个选项,例如:back.但是不行.
Here is what I have for redirecting to a default url(myapp_url). But I want to change redirect to go the request url was entered by the user after authentication. How do I do that? I tried couple of options from searching here, like :back. But no go.
用户输入一个url,如果没有通过认证则被重定向到登录页面,然后登录后用户将被重定向到原始请求url.
User enters an url, if not authenticated then gets redirected to the login page, then after login user shall be redirected to the original request url.
def create
user = User.Authenticate(params[:user_id], params[:password])
if user
session[:user_id] = user.id
redirect_to myapp_url, :notice => "Logged in!"
else
flash.now.alert = "Invalid email or password"
render "new"
end
end
推荐答案
您可以阅读 Michael Hartl 撰写的Ruby on Rails 教程"中关于友好转发"的章节,了解如何轻松实现它.
You can read the chapter about "Friendly forwarding" in the "Ruby on Rails Tutorial" by Michael Hartl to see how you can easily implement it.
基本上你有 3 个辅助方法:
Basically you have 3 helper methods:
store_location
在会话中存储用户想要的位置redirect_back_or(url)
将用户重定向到会话中存储的位置,如果未设置,则重定向到url
方法参数中包含的位置- 和
clear_return_to
被redirect_back_or
方法内部"使用以清除使用过的这条信息
store_location
to store the user desired location in the sessionredirect_back_or(url)
redirect the user to the location stored in the session or, if not set, to the location contained in theurl
method param- and
clear_return_to
used "internally" by theredirect_back_or
method to clear this piece of information once used
然后你使用这些方法:
A) 当您看到访客用户尝试访问需要身份验证的页面时,请使用 store_location
,然后将他重定向到登录页面.
B) 当用户登录时,您使用 redirect_back_or(url)
将他重定向到正确的位置(当然如果存在)
A) when you see a guest user try to access a page that needs authentication use store_location
before redirect him to the login page.
B) when a user is logged in, you use redirect_back_or(url)
to redirect him to the right location (if present of course)
这是它如何工作的概述,您明白了,但我建议阅读该章节以了解实现(少数)细节.
This is an overview of how this work, you get the idea but I suggest to read that chapter for the implementation (few) details.
这篇关于ruby rails - 重定向到原始请求 url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!