eas*_*ent 182 redirect ruby-on-rails
我有一个页面列出了所有具有可排序标题和分页的项目.
path:
/projects?order=asc&page=3&sort=code
Run Code Online (Sandbox Code Playgroud)
我选择编辑其中一个项目
path:
projects/436/edit
Run Code Online (Sandbox Code Playgroud)
当我单击该页面上的save时,它会调用项目控制器/更新方法.在我更新代码之后,我想在我点击编辑特定项目之前重定向到我所在的路径.换句话说,我希望使用相同的排序在同一页面上.
我看到了link_to(:back)并认为:back可以在redirect_to(:back)中工作,但那是不行的.
puts YAML::dump(:back)
yields the following:
:back
Run Code Online (Sandbox Code Playgroud)
关于如何让这个工作的任何想法.这似乎是一个容易解决的问题,但我是RoR的新手.
Jai*_*yer 319
在您的编辑操作中,将请求网址存储在会话哈希中,该哈希值可用于多个请求:
session[:return_to] ||= request.referer
Run Code Online (Sandbox Code Playgroud)
在成功保存后,在更新操作中重定向到它:
redirect_to session.delete(:return_to)
Run Code Online (Sandbox Code Playgroud)
Pas*_*cal 97
为什么不redirect_to(:back)适合你,为什么不行?
redirect_to(:back)对我来说就像是一种魅力.这只是一个捷径
redirect_to(request.env['HTTP_REFERER'])
http://apidock.com/rails/ActionController/Base/redirect_to(前Rails 3)或http://apidock.com/rails/ActionController/Redirecting/redirect_to(Rails 3)
请注意,redirect_to(:back)在Rails 5中已弃用.您可以使用
redirect_back(fallback_location: 'something')相反(参见http://blog.bigbinary.com/2016/02/29/rails-5-improves-redirect_to_back-with-redirect-back.html)
Ton*_*ony 45
我喜欢Jaime的方法,只有一个例外,每次重新存储引用者对我来说效果更好:
def edit
session[:return_to] = request.referer
...
Run Code Online (Sandbox Code Playgroud)
原因是如果您编辑多个对象,您将始终被重定向回使用Jaime方法存储在会话中的第一个URL.例如,假设我有Apple和Orange的对象.我编辑Apple并session[:return_to]设置为该操作的引用者.当我使用相同的代码编辑橘子时,session[:return_to]不会因为已经定义而设置.因此,当我更新Orange时,我将被发送给之前Apple#edit动作的引用者.
MBO*_*MBO 33
这就是我们在应用程序中执行此操作的方式
def store_location
session[:return_to] = request.fullpath if request.get? and controller_name != "user_sessions" and controller_name != "sessions"
end
def redirect_back_or_default(default)
redirect_to(session[:return_to] || default)
end
Run Code Online (Sandbox Code Playgroud)
这样,您只在:return_to会话参数中存储最后一个GET请求,因此所有表单,即使多次POSTed都可以使用:return_to.
小智 18
request.referer 由Rack设置,设置如下:
def referer
@env['HTTP_REFERER'] || '/'
end
Run Code Online (Sandbox Code Playgroud)
只需执行一次redirect_to request.referer,它将始终重定向到真正的引用页面或root_path('/').当将直接导航失败的测试传递给控制器抛出redirect_to的特定页面时,这是必不可少的:返回
pSk*_*arl 17
在rails 5中,根据Rails指南中的说明,您可以使用:
redirect_back(fallback_location: root_path)
Run Code Online (Sandbox Code Playgroud)
"后退"位置是从HTTP_REFERER标头中提取的,不保证由浏览器设置.这就是为什么你应该提供'fallback_location'.
| 归档时间: |
|
| 查看次数: |
152853 次 |
| 最近记录: |