Rails 如何保存请求的 url? [英] Rails how to save the requested url?
问题描述
我有两种不同的方式来访问 url "localhost:3000/childrens/new".
I have two different ways to access the url "localhost:3000/childrens/new".
我在 childrens/new 页面中有一个下拉列表,当用户通过下拉列表选择一个选项时,它会显示使用 ajax 调用 childrens#new 方法的不同部分.
I have a drop down in childrens/new page and when the user selects an option through the drop down, it shows the different partials using ajax to call the childrens#new method.
- 从 url "localhost:3000/parents" 访问孩子的新页面
- 从 url "localhost:3000/parents1" 访问孩子的新页面
子节点创建成功后,用户应该被重定向到相关的 url(localhost:3000/parents 或 localhost:3000/parents1)
After the children have been successfully created, the user should be redirected to the relevant url (either localhost:3000/parents or localhost:3000/parents1)
推荐答案
实现这一目标的方法不止一种.
There are more than one way of how you can achieve this.
一种解决方案是在请求 childs/new 时将引用者存储在 session/cookie 中:(在 children_controller 中)
One solution would be to store the referrer inside of the session/cookie when the childrens/new is requested: (inside children_controller)
def new
session['children_new_referrer'] = request.env["HTTP_REFERER"]
#....YOUR CODE....
end
然后使用存储在 session/cookie 中的引用值来适当地重定向:
And then using that referrer value stored in session/cookie to redirect appropriately:
def create
#.....YOUR CODE....
if @child.save
format.html {redirect_to (session['children_new_referrer'] || parents_path)}
#.....YOUR CODE....
end
其中@child 是我假设您正在使用参数构建的对象,并且 parents_path 是通过您的路由定义的.您可以根据自己的需要随意调整这两个.
where @child is the object which I assume you are building with the parameters, and parents_path is being defined through your routes. Feel free to adjust these two based on your needs.
另一种解决方案是不使用会话,而是将引用 uri/path 保存在子/新表单页面本身内.这种替代方法的好处是使解决方案会话/请求范围独立于处理在页面范围内存储引用 uri/路径的要求.
An alternative solution would be to not use sessions, but instead save the referrer uri/path inside of the children/new form page itself. This alternative has the benefit of making the solution session/request scope independent with handling the requirement of storing the referral uri/path within the page scope.
这篇关于Rails 如何保存请求的 url?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!