【问题标题】:if, elsif, else statements html erb beginnerif, elsif, else 语句 html erb 初学者
【发布时间】:2014-11-10 19:58:25
【问题描述】:

我在 html.erb 中遇到了 if、elsif、else 语句的问题。我在 erb 中看到了很多关于 if/else 语句的问题,但没有一个包含 elsif,所以我想我会寻求帮助。

这是我的 html.erb:

<% if logged_in? %>

          <ul class = "nav navbar-nav pull-right">
          <li class="dropdown">
            <a href="#" class="dropdown-toggle" data-toggle="dropdown">
              Account <b class="caret"></b>
            </a>

          <ul class="dropdown-menu pull-right">
                  <li><%= link_to "Profile", current_user %></li>
                  <li><%= link_to "Settings", edit_user_path(current_user) %></li>
                  <li class="divider"></li>
                  <li>
                    <%= link_to "Log out", logout_path, method: "delete" %>
            </li>
          </ul>
          </li>
        </ul>



     <% elsif has_booth?(current_user.id) %>

      <ul>

        <li>TEST</li>

      </ul>



<% else %>
        <ul class="nav navbar-nav pull-right">
          <li><%= link_to "Sign Up", signup_path %></li>
          <li><%= link_to "Log in", login_path %></li>
        </ul>
      <% end %>

这是我的 has_booths 方法:

module BoothsHelper

def has_booth?(user_id)
  Booth.exists?(user_id: user_id)
end 

end

我希望标题导航为不同的用户提供三种不同类型的内容。已登录用户、已创建展位的已登录用户和已注销用户。到目前为止,我似乎只能完成三项工作中的两项。我尝试改变

<% elsif has_booth?(current_user.id) %>

<% elsif logged_in? && has_booth?(current_user.id) %>

这也不起作用。我的陈述是否正确?任何想法表示赞赏。谢谢。

【问题讨论】:

    标签: ruby-on-rails-4 erb


    【解决方案1】:

    问题是你的第一个条件是真的,所以它停在那里。你的第一个条件:

    <% if logged_in? %>
    

    即使他们没有展位,它也永远不会到达 elsif,因为第一个条件为真。你要么需要:

    <% if logged_in? && has_booth?(current_user.id) %>
      // code
    <% elsif logged_in? && !has_booth?(current_user.id) %>
      // code
    <% else %>
      // code
    <% end %>
    

    或者将它们分成两个 if/else 可能是一种更简洁的方法:

    <% if logged_in? %>
      <% if has_booth?(current_user.id) %>
        // code
      <% else %>
        // code
      <% end %>
    <% else %>
      // code
    <% end %>
    

    【讨论】:

    • 感谢您的解释。我实施了第一个解决方案,它奏效了。至于清洁工,如果两个实例都为真,第一个代码块是否会是,如果只有logged_in,第二个代码块会是吗?是真的,第三块为其他?再次感谢。
    • 不客气,是的,这与您概述更清洁方法的方式是正确的。
    【解决方案2】:

    更简洁的方法是将语句展平,首先处理未登录的情况,这样您就不必测试它以及他们是否有展位:

    <% if !logged_in? %>
      // not logged in code
    <% elsif has_booth?(current_user.id) %>
      // logged in and has booth code
    <% else %> 
      // logged in and does not have booth code
    <% end %>
    

    您也可以使用 unless logged_in?,但 else 和 elsif 在语义上没有那么大的意义,因为使用了除非,因此读起来不那么清楚。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-24
      • 2015-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多