2010-05-27 46 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