简体   繁体   中英

Show object with unless and else Ruby

I want to use unless with else statement. I want in the else statement to make sure the object is not nil first (so, it won't break) then it is not nil print the user.employers.first.name in the else.

<% unless user.employers.empty? || (user.employers.size < 2) %>
                <%= link_to user.employers.first.name,show_companies_user_path(user), "data-toggle" => "modal","data-target" => "#myModal" %>
                   (<%=user.employers.size %>)
              <% else %>
                <%= user.employers.present?%>
                 <%= user.employers.first.name %> # I want to show this
              <% end %>

You can use unless that way, but unless - else is a very weird pattern. The whole point of unless is to have a simple shortcut for if not but if you have an if *positive* else *alternative* type pattern then starting with unless is a less readable than starting with if .

I've never really seen this pattern before. You should do the if else pattern in my opinion. Just negate the logic behind unless and use if .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM