Mary P. Mary P. - 3 months ago 21
Ruby Question

Bootstrap Accordion collapse with Ruby hash

Collapse is only working on the first button, and I know it's because only the first div id is being set for all buttons. How do I iterate and make new div id's for each element when using hash.each?

Here's my erb:

<% @contacts.each do |category, hash| %>
<div class="panel-group" id=accordion">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"><%= category %></h3>
</div>
<div class="panel-body">
<ul class="list-group">
<% hash.each do |contact| %>
<li class="list-group-item" style="border: none">
<button type="button" class="btn btn-info" data-toggle="collapse" data-parent="#accordion" data-target="#demo"><%= contact['name'] %></button>
<div id="demo" class="panel-collapse collapse">
<div class="panel-body"><%= contact['email'] %></br><%= contact['ext'] %>
</div>
</div>
</li>
<% end %>
</ul>
</div>
</div>
</div>
<% end %>


Here's the corresponding code from my .rb:

get '/contact' do
contact = Contacts.new
@contacts = contact.getContacts
@contacts.each { |s| puts "get /contact found contact #{s.last.first['name']}" }
erb :contact

Answer

try

<% hash.each_with_index do |contact, index| %>
    <li class="list-group-item" style="border: none">
    <button type="button" class="btn btn-info" data-toggle="collapse" data-parent="#accordion" data-target="#collapse<%= index %>"><%= contact['name'] %></button>
    <div id="collapse<%= index %>" class="panel-collapse collapse">
        <div class="panel-body"><%= contact['email'] %></br><%= contact['ext'] %>
        </div>
    </div>
   </li>
<% end %>