If, elsif, else statements html erb beginner

I am having problems with if, elsif, else statment in html.erb. I saw a lot of questions around if / else statements in erb, but none of them include elsif, so I thought I would ask for help.

Here is my 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 %> 

Here is my has_booths method:

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

I would like the nav header to have three different types of content for different users. Registered user, registered user who created the stand, and logged out user. So far, I can only do 2 of three jobs. I tried to change

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

to

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

and that didn't work either. Am I spelling my expression correctly? Any thoughts appreciated. Thank you

+5
source share
1 answer

The problem is that your first condition is true, so it stops. Your first condition:

 <% if logged_in? %> 

Even if they do not have a stand, he will never reach elsif, because the first condition is true. You either need to:

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

Or it could be a cleaner approach to split them into two if / else:

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

Source: https://habr.com/ru/post/1206584/


All Articles