M
M
Max2016-03-20 19:31:44
Ruby on Rails
Max, 2016-03-20 19:31:44

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 %>

For obvious reasons, it first prints the
<div class="place_block" style=""><%= n %></div>
A block, then
<div class="place_block" style="background-color: black"><%= n %></div>

With the same number.
The rest of the entries are displayed without duplicates. Tell me how to solve this problem, I can not logically think of a solution.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mikhail Beloshitsky, 2016-03-20
@mbeloshitsky

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 %>

But in a good way, you need to modify models / controllers, in code templates
should not be.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question