我根据当前页面在导航栏中显示某些项目。当我进入我的登录页面时,会显示正确的项目。如果我使用不正确的密码登录,项目会更改并且不正确。
在我的html中我检查if (current_page?(new_user_session_path))
提交不正确的密码并重新加载页面后,此条件未返回 true,并且在导航栏中显示错误的项目。我查看了服务器日志上的请求,我猜这是因为页面在 POST 之后第二次加载(密码提交不成功)。我需要第二次检查不同的路径吗?
我根据当前页面在导航栏中显示某些项目。当我进入我的登录页面时,会显示正确的项目。如果我使用不正确的密码登录,项目会更改并且不正确。
在我的html中我检查if (current_page?(new_user_session_path))
提交不正确的密码并重新加载页面后,此条件未返回 true,并且在导航栏中显示错误的项目。我查看了服务器日志上的请求,我猜这是因为页面在 POST 之后第二次加载(密码提交不成功)。我需要第二次检查不同的路径吗?
扩展 Scott 的答案,您可以在app/helpers/navigation_helper.rb中创建一个助手,例如,如下所示:
module NavigationHelper
def current_location?(*args)
options = args.extract_options!
options.each do |key, val|
return false unless eval("controller.#{key.to_s}_name") == val
end
true
end
end
并以这种方式使用它:
current_location?(controller: 'my_controller', action: 'new')
current_location?(controller: 'my_controller')
current_location?(action: 'new')
在您看来,您可以执行以下操作:
# Change this according what your really need
if current_location?(controller: 'sessions', action: 'new')
希望能帮助到你 ; )
如果你查看 的源代码current_page?
,如果请求的 HTTP 模式不是 GET 或 HEAD,它总是返回 false:
http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-current_page-3F
def current_page?(options)
unless request
raise "You cannot use helpers that need to determine the current " "page unless your view context provides a Request object " "in a #request method"
end
return false unless request.get? || request.head?
...
因此,即使您的错误形式与 完全相同new_user_session_path
,您的逻辑也不会匹配。
您可能需要考虑直接controller.controller_name
比较controller.action_name
。不完全优雅,但它会更可靠。