Rails multiple if statement list all conditions met on output text

Viewed 62

I have a Poll app where users can vote. Each Poll has conditions that allow users to vote or not.

Right now I'm doing:

    <% if current_user.voted_for?(@poll)  %>

    <p>You already voted this poll</p>


    <% elsif @poll.open_date > Date.today %>
    <p>Poll is not opened yet</p>


    <% elsif @poll.close_date < Date.today %>
    <p>Poll is already closed</p>

    <% elsif current_user.polls.exists?(@poll.id) %>
    <p>You are not allowed to vote on this poll</p>

    <% elsif current_user.chair_role? %>
    <p>BOD chair role is not allowed to vote</p>
    <% else %>

    <%= submit_tag 'Vote', class: 'btn btn-lg btn-primary' %>
  <% end %>

First condition met returns corresponding text and won't check next conditions.

How can I instead list on output text all conditions met?

For instance

Poll is already closed
You already voted this poll

How can I do that?

1 Answers

You can use a string to append text and you'll need multiple separate if statements.

<%
  output = ""
  output << "You already voted in this poll. " if current_user.voted_for?(@poll)
  output << "Poll is not open. " if @poll.open_date > Date.today
%>

<% if output.blank? %>
  <%= submit_tag 'Vote', class: 'btn btn-lg btn-primary' %>
<% else %>
  <%= output %>
<% end %>
Related