Answer the question
In order to leave comments, you need to log in
How to prevent duplicate entry in a loop?
Hello, I have a loop like this:
<% @session.number_of_session_places.times do |session| %>
<% n = n+1 %>
<div class="place_block" style=""><%= n %></div>
<% @session.places.each do |p| %>
<% if p.place_number == n %>
<div class="place_block" style="background-color: black"><%= n %></div>
<% end %>
<% end %>
<% end %>
<div class="place_block" style=""><%= n %></div>
<div class="place_block" style="background-color: black"><%= n %></div>
Answer the question
In order to leave comments, you need to log in
The main problem with this code is the wrong data structures. Therefore, you have two cycles here, although, logically, only one is needed. Based on what is already there, I would do something like this:
<% reserved = Hash[ @session.places.map { |p| [p.place_number, p] } ] %>
<% @session.number_of_session_places.times do |session| %>
<% n = n+1 %>
<div style="<%= reserved.include? n ? 'background: black;' : '' %>">
<%= n %>
</div>
<% end %>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question