1

サブ URL に似たものを使用する方法を探していlink_to_unless_currentます。たとえば、これらの両方の URL の場合:

/entity_name/
/entity_name/123

リンクにはなりません。Railsでそれを達成するにはどうすればよいですか?

UPD:自分のカスタム方法で解決しました。Ruby に詳しい方、よろしければ教えてください。

module ApplicationHelper

  def link_to_unless_current_or_sub(name, options = {}, html_options = {}, &block)
    link_to_unless current_page_or_sub?(options), name, options, html_options, &block
  end

private

  def current_page_or_sub?(options)
    url_string = CGI.unescapeHTML(url_for(options))
    request = @controller.request
    if url_string.index("?")
      request_uri = request.request_uri
    else
      request_uri = request.request_uri.split('?').first
    end

    request_uri.starts_with?(url_string)
  end

end

使用法:

<%= link_to_unless_current_or_sub("Users", users_path) %>
4

2 に答える 2

0

Rails 3.2 で動作しますが、若干の調整が必要です

def current_page_or_sub?(options)
  url_string = CGI.unescapeHTML(url_for(options))
  if url_string.index("?")
    request_url = request.fullpath
  else
    request_url = request.fullpath.split('?').first
  end
  request_url.starts_with?(url_string)
end
于 2013-10-21T16:08:53.850 に答える
0

そのようなヘルパーメソッドは存在しないと思います

次のようなものを書く必要があります

<% if params[:id] %>
       "Home"
<% else %>
       <%= link_to "Home", { :action => "index" }) %>
<% end %>
于 2010-05-27T14:39:13.067 に答える