我的Rails 2.3应用程序具有用户模型和通常的控制器操作.编辑表单可以通过两种方式实现:当用户从主页编辑自己的个人资料时,或者管理员用户从用户集合编辑其他人的个人资料时.
我想要做的是让更新操作重定向回引用的编辑操作,而不是更新操作.如果我在更新中做一个简单的redirect_to(:back),它会回到编辑表单 - 不好.
一种解决方案是完全忘记引用和基于current_user和更新用户的重定向:如果它们相同,则返回主页,否则转到用户集合页面.如果我向编辑表单添加第三个路径,这将会中断.令人怀疑的是我会做到这一点,但我更喜欢一种不那么脆弱的解决方案.
另一种解决方案是将编辑表单的引用者存储在隐藏字段中,然后从更新操作内部重定向到该值.这感觉不太对劲,但我无法解释原因.
还有更好的方法吗?或者,我是否应该停止担心并选择我提到的两个中的一个?
您可以在会话中记住该网址.这就是我在我的应用程序中实现此功能的方法.
将这些方法添加到ApplicationController中
def store_location location=nil
session[:return_to] = location || request.request_uri
end
def redirect_back_or_default(default)
redirect_to(session[:return_to] || default)
session[:return_to] = nil
end
def http_referrer
http_referer, request_path = request.env["HTTP_REFERER"],
request.env["REQUEST_PATH"]
return nil unless (http_referer and request_path and
http_referer =~ Regexp.new("^#{SITE_ROOT}") and
http_referer != (SITE_ROOT + request_path))
return http_referer
end
Run Code Online (Sandbox Code Playgroud)
在UserController edit/new行动中存储推荐人.
before_filter :store_location, :only => [:new, :edit]
def store_location
super http_referrer
end
Run Code Online (Sandbox Code Playgroud)
在UserController create/update操作中返回并重置引用者.
def create
if @user.save
flash[:notice] = "Successfully created the user."
redirect_back_or_default root_url
else
render :action => 'new'
end
end
def update
if @user.save
flash[:notice] = "Successfully created the user."
redirect_back_or_default root_url
else
render :action => 'new'
end
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1698 次 |
| 最近记录: |