【问题标题】:Making a conditional link_to statement in Rails?在 Rails 中制作条件 link_to 语句?
【发布时间】:2012-06-27 19:23:46
【问题描述】:

在下面的代码中,我试图做到这一点,如果用户接受了邀请,他们将能够点击“不参加” div 来拒绝邀请。

那一点逻辑工作得很好,但我试图得到它,所以无论用户是否接受了邀请,都会显示“不参加”的 div。

目前,只有当用户接受了邀请时,该 div 才会出现。

有没有办法使 link_to 语句有条件,但无论如何都保留 div? (也就是说,让 div 始终存在,但如果用户接受了邀请,它只是一个链接?)

<% if invite.accepted %>
    <%= link_to(:controller => "invites", :action => "not_attending") do %>                             
        <div class="not_attending_div">
             not attending
        </div>
    <% end %>
<% end %>

【问题讨论】:

    标签: ruby-on-rails link-to


    【解决方案1】:
    <%= link_to_if invite.accepted ... %>
    

    http://apidock.com/rails/ActionView/Helpers/UrlHelper/link_to_if

    编辑:

    link_to_if 使用 link_to_unless 使用 link_to 的代码,它应该与相同的选项工作相同

      def link_to_unless(condition, name, options = {}, html_options = {}, &block)
        if condition
          if block_given?
            block.arity <= 1 ? capture(name, &block) : capture(name, options, html_options, &block)
          else
            name
          end
        else
          link_to(name, options, html_options)
        end
      end
    

    例子

    <%=
       link_to_if(@current_user.nil?, "Login", { :controller => "sessions", :action => "new" }) do
         link_to(@current_user.login, { :controller => "accounts", :action => "show", :id => @current_user })
       end
    %>
    

    在这里查看http://apidock.com/rails/ActionView/Helpers/UrlHelper/link_to_unless

    编辑:

    这是否满足您的需求。抱歉,没有更好地阅读问题。

    <div class="not_attending_div">
       <%= link_to_if invite.accepted, "not attending", (:controller => "invites", :action => "not_attending") %>
    </div>
    

    【讨论】:

    • 这可能会做到。我需要先玩一下。现在的主要问题是让它接受 div 作为链接名称。
    • 不幸的是,我无法将 not_attending div 作为名称参数。而且 API 看起来好像 link_to_if 方法没有那么多选项。
    • 实际上,我确实也查看了 link_to_unless API。但是,我仍然没有看到用 div 替换所需的“名称”参数的方法。如果我尝试不使用它,它只会将选项转换为纯文本并将其用作链接名称。如果我尝试包含实际的 div html 作为名称参数,它就会爆炸。
    • 我仍然无法让它工作,但我非常感谢您的帮助。我必须继续前进,但是当我有时间时,我可能会回到这个问题上。再次感谢!
    • 这是我的荣幸。抱歉,我在处理错误时快速阅读了这个问题。
    【解决方案2】:

    刚刚在这里回答:How to create a link_to_if with block only if condition is met?

    如果您仍然想显示该块,但仅在满足特定条件时添加链接,您可以完全捕获该块并在简单的条件下使用它:

    <% block_content = capture do %>
      <div class="not_attending_div">
        not attending
      </div>
    <% end %>
    
    <% if invite.accepted %>
      <%= link_to block_content, controller: :invites, action: :not_attending %>
    <% else %>
      <%= block_content %>
    <% end %>
    

    【讨论】:

      猜你喜欢
      • 2016-06-25
      • 1970-01-01
      • 2019-05-31
      • 1970-01-01
      • 2013-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多