【问题标题】:Rails link_to_if not hiding links correctlyRails link_to_if 没有正确隐藏链接
【发布时间】:2018-01-24 19:44:47
【问题描述】:

由于某种原因,我的 link_to_if 行有效,但出现在我的模型(公司)的每个展示视图中。

代码如下:

<% @customers.each do |customer| %>
  <li>
    <%= link_to_if customer.company_id == @company.id, "#{customer.first_name} #{customer.last_name}", customer_path(customer[:id]) %>
  </li>
<% end %>

问题:我将 Customer1 链接到 CompanyX。当我转到 CompanyZ 时,它显示 Customer1,但链接不是超链接。它只是纯文本,甚至不应该出现。然而,在 CompanyX 看来,该链接工作正常。我在这里做错了什么?

【问题讨论】:

    标签: ruby-on-rails hyperlink hide link-to


    【解决方案1】:

    如果你阅读了link_to_if (https://apidock.com/rails/ActionView/Helpers/UrlHelper/link_to_if) 的文档,它清楚地表明[if false] 只返回名称

    在文档中,您可以发现给定的(可选)块是在 false 情况下呈现的。因此,在您的情况下,您可以将其传递给一个空块:

    <%= link_to_if false, customer_path(customer[:id]) {} %>
    

    在我看来,如果您只想在@customers 中的一个或多个customer(s) 与该@company 关联时才显示链接,您应该这样做:

    <% @customers.where(company_id: @company.id).each do |customer| %>
      <li>
        <%= link_to "#{customer.first_name} #{customer.last_name}", customer_path(customer[:id]) %>
      </li>
    <% %>
    

    【讨论】:

    • 由于某种原因,空块不起作用,但是来自文档link_to "Login", ... if @current_user.nil? 为我工作。谢谢。
    • @SamLim 我强烈建议您看一下我答案的第二部分,因为它会节省性能。循环遍历所有 @customers 数组只显示匹配的 customer@company 是浪费性能。
    • 是的,完美运行!非常感谢。作为一个 Rails 新手,还有一个问题……这种类型的逻辑应该在视图中吗?
    • 不,在你的控制器中你可能有类似@customers = Customer.all的东西。将其替换为 @customers = Customer.where(company_id: @company.id) 以仅从该公司获取客户。更好的方法(更具可读性)是使用@customers = @company.customers,甚至直接在您的视图中使用@company.customers.each do |customer|
    【解决方案2】:

    如果您想隐藏一些记录,您可以从控制器到控制基于客户的公司进行操作

    @customers = Company.find(:id).customers
    

    那么在你的观点中你可以直接展示它而不进行比较

    <% @customers.each do |customer| %>
      <li>
        <%= link_to "#{customer.first_name} #{customer.last_name}", customer_path(customer[:id]) %>
      </li>
    <% end %>
    

    【讨论】:

      猜你喜欢
      • 2015-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-18
      • 1970-01-01
      • 2013-11-06
      • 2016-12-29
      • 1970-01-01
      相关资源
      最近更新 更多