2010-05-27 45 views
1

我正在寻找一种方式来使用类似link_to_unless_current的东西,但对于子URL,因此,例如用于这两个网址:link_to_unless_current在Rails的subURLs

/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) %> 

回答

0

我不认为这样的辅助方法存在

你必须写类似以下

<% if params[:id] %> 
     "Home" 
<% else %> 
     <%= link_to "Home", { :action => "index" }) %> 
<% end %> 
+0

我不想这样做,因为我可以在entity_name:/ blogs/1/comments下面有内部控制器。 – Vitaly 2010-05-27 14:54:23

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