Rails current_page?方法是POST时"失败"

Jas*_*ett 7 ruby-on-rails-3

我有一个非常简单的问题.我有一页报告,每个报告都有自己的标签.我正在使用它current_page?来确定应突出显示哪个选项卡.当我提交任何报告时,current_page?似乎不再起作用,显然是因为请求方法是POST.

这是current_page?我的预期行为,我很难想象为什么会是这种情况.如果是,人们通常如何解决这个问题?

这是一个current_page?电话的例子:

<li><%= link_to "Client Retention", reports_client_retention_path, :class => current_page?(reports_client_retention_path) ? "current" : "" %></li>

Jas*_*ett 11

好吧,看起来我在提出赏金后约5分钟就找到了自己问题的答案.看起来current_page?总是会返回false POST.

这是源代码current_page?:

# File actionpack/lib/action_view/helpers/url_helper.rb, line 588
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?

  url_string = url_for(options)

  # We ignore any extra parameters in the request_uri if the
  # submitted url doesn't have any either. This lets the function
  # work with things like ?order=asc
  if url_string.index("?")
    request_uri = request.fullpath
  else
    request_uri = request.path
  end

  if url_string =~ %r^\w+:\/\//
    url_string == "#{request.protocol}#{request.host_with_port}#{request_uri}"
  else
    url_string == request_uri
  end
end
Run Code Online (Sandbox Code Playgroud)

我真的不明白为什么他们会竭尽全力current_page?只为GET请求做工作,但至少现在我知道那就是它的方式.

  • 如果其他人有同样的挫折感,我在这里找到了对'current_page?`"问题"的解决方法:http://stackoverflow.com/questions/5186613/rails-current-page-versus-controller-controller-名称 (5认同)

Mat*_*dan 5

您可以在您的中创建一个新current_path?方法ApplicationHelper

def current_path?(*paths)
  return true if paths.include?(request.path)
  false
end
Run Code Online (Sandbox Code Playgroud)

传入一个或多个路径,如果有匹配用户当前路径,则返回 true:

current_path?('/user/new')
current_path?(root_path)
current_path?(new_user_path, users_path '/foo/bar')
Run Code Online (Sandbox Code Playgroud)

或者,您可以创建一个新的current_request?辅助方法来检查 Rails 控制器 + 操作:

def current_request?(*requests)
  return true if requests.include?({
    controller: controller.controller_name,
    action: controller.action_name
  })
  false
end
Run Code Online (Sandbox Code Playgroud)

传入一个或多个控制器 + 操作,如果有匹配用户当前请求,则返回 true:

current_request?(controller: 'users', action: 'new')
current_request?({controller: 'users', action: 'new'}, {controller: 'users', action: 'create'})
Run Code Online (Sandbox Code Playgroud)

==更新==

好吧,我决定在current_request?尝试匹配多个操作时不要求您键入控制器,从而使使用不再那么冗长:

def current_request?(*requests)
  requests.each do |request|
    if request[:controller] == controller.controller_name
      return true if request[:action].is_a?(Array) && request[:action].include?(controller.action_name)
      return true if request[:action] == controller.action_name
    end
  end
  false
end
Run Code Online (Sandbox Code Playgroud)

现在你可以这样做:

current_request?(controller: 'users', action: ['new', 'create'])
Run Code Online (Sandbox Code Playgroud)