ruby-on-rails - 获取渲染以识别自定义路由路径

标签 ruby-on-rails ruby

所以我有一个时髦的自定义登录路径

# routes.rb
map.login '/login', :controller => 'sessions', :action => 'new'

访问 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

这很典型。只需呈现新操作并提示再次登录。不幸的是,您还会得到一个丑陋的 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

请注意,您需要更改 flash,以便消息在下一个请求中可用(在重定向之后)。

第二种方法稍微复杂一些,但也许值得一提。通过在路由上使用条件,您可以将登录表单(GET)和表单提交(POST)映射到同一路径。像这样的东西:

map.login '/login',
  :controller => 'sessions', :action => 'new', 
  :conditions => {:method => :get}

map.login_submit '/login',
  :controller => 'sessions', :action => 'create', 
  :conditions => {:method => :post}

然后,如果您的表单操作是登录提交路径,那么事情应该会如您所愿。

关于ruby-on-rails - 获取渲染以识别自定义路由路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/231538/

相关文章:

python - 检查我的脚本是否启动且未卡住的可靠方法是什么?

ruby-on-rails - 事件管理员 NoMethodError 错误

ruby-on-rails - rails ActiveRecord 对特定 Controller 和 Action 的验证

sql - postgresql,奇怪的 OFFSET/LIMIT 行为(记录顺序)

ruby-on-rails - Rails 时间戳与 mysql 时间戳不同

ruby-on-rails - ruby rails : CSS and skins management

ruby-on-rails - Netflix API、OAuth 和 Ruby 问题

ruby-on-rails - ROR 将参数传递给模态

mysql - 无法在 Windows 7 64 位上安装 openproject - Fiddle :Module 的未定义方法 `dlopen'

arrays - 将散列视为数组?