【问题标题】:How to use the `link_to_unless_current` helper to work for both current or root path?如何使用 `link_to_unless_current` 帮助器同时为当前路径或根路径工作?
【发布时间】:2017-06-19 17:51:03
【问题描述】:

我正在设置我的导航栏link_to,如果 current_path 与 link_path 相同或当前路径与根路径相同,我试图停止呈现链接,因为根路径被定义为与链接路径相同,如下:

_navbarhtml.erb

        <ul class="nav navbar-nav navbar-right">
         <% if user_signed_in? %>               
           <li><%= link_to_unless_current('My Quotes', quotes_path(current_user)) do %></li>
         <% end %>
           <li><%= link_to_unless_current('New Quote', new_quote_path) do %></li>
         <% end %>
           <li><%= link_to('My Account', edit_user_registration_path) %></li>
           <li><%= link_to "Sign out", destroy_user_session_path, :method => :delete %></li>
         <% else %>
           <li><%= link_to('Sign in', new_user_session_path) %></li>
           <li><%= link_to('Sign up', new_user_registration_path) %></li>
         <% end %>
        </li>

routes.rb

root    'quotes#new'

关于如何写好这篇文章有什么好的建议吗?

【问题讨论】:

标签: ruby-on-rails actionviewhelper


【解决方案1】:

你可以试试current_page?。像这样创建一个辅助方法:

def link_to_unless_current(text, url, options={})
  if current_page?(url)
    # do something else? maybe create a text which does not have a link?
  else
    link_to text, url, options
  end
end

现在,视图将是这样的:

<%= link_to_unless_current('My Quotes', quotes_path(current_user)) %>

随意更改辅助方法的名称。

【讨论】:

    【解决方案2】:

    感谢 Surya,这就是我最终让它工作的方式:

    application_helper.rb

    def link_to_unless_current_or_root(text, url)
        if current_page?(url) 
    
        elsif current_page?(root_path)
    
        else
            link_to text, url
        end
    end
    

    _navbar.html.erb

    <li><%= link_to_unless_current_or_root('New Quote', new_quote_path) %></li>
    

    【讨论】: