Bar*_*ess 5 ruby ruby-on-rails
所以我有一个时髦的自定义登录路线
# routes.rb
map.login '/login', :controller => 'sessions', :action => 'new'
Run Code Online (Sandbox Code Playgroud)
访问www.asite.com/login,你就在那里.但是,对于登录失败的自定义,我们将在操作中执行以下操作.请注意登录失败时会发生什么.
# sessions_controller.rb
def create
self.current_user = User.authenticate(params[:email], params[:password])
if logged_in?
# some work and redirect the user
else
flash.now[:warning] = "The email and/or password you entered is invalid."
render :action => 'new'
end
end
Run Code Online (Sandbox Code Playgroud)
这很典型.只需渲染新操作并再次提示登录.不幸的是,你也会得到一个丑陋的URL:www.asite.com/session.伊克!是否可以让渲染尊重原始URL?
您的问题是:用户首先访问/login并填写表单.当他们提交表单时,他们会POST到/sessions,这就是浏览器URL更改的原因.要解决这个问题,你可以做两件事:
正如Michael所提到的,您可以重定向回:new操作,将else更改为:
else
flash[:warning] = "The email and/or password you entered is invalid."
redirect_to login_path
end
Run Code Online (Sandbox Code Playgroud)
请注意,您需要更改闪存,以便在下一个请求中提供消息(重定向之后).
第二种方法略显粗俗,但也许值得一提.通过在路由上使用条件,您可以将登录表单(这是一个GET)和表单提交(这是一个POST)映射到同一路径.就像是:
map.login '/login',
:controller => 'sessions', :action => 'new',
:conditions => {:method => :get}
map.login_submit '/login',
:controller => 'sessions', :action => 'create',
:conditions => {:method => :post}
Run Code Online (Sandbox Code Playgroud)
然后,如果您的表单操作是登录提交路径,那么事情应该按预期工作.