Iterating over rails object and array
I am iterating over the @products model object (currently 3 in the DB), but I also need to apply different styles to each of the objects returned in my view.
Here is my current code in my page_controller.rb to get only the first 3 products:
@products = Product.where(id: 1..3)
In my opinion index.html.erb :
<div class="row pricing-table">
<% @products.each do |p| %>
<div class="col-md-4">
<div class="panel <%= custom-style %>">
<div class="panel-heading"><h3 class="text-center"><%= p.title %></h3></div>
<div class="panel-body text-center">
<p class="lead" style="font-size:40px"><strong><%= number_to_currency(p.price, precision: 0) %>/month</strong></p>
</div>
<ul class="list-group list-group-flush text-center list-no-bullets">
<%= p.description.html_safe %>
</ul>
<div class="panel-footer">
<%= link_to("Request Quote", "/quote_forms/new", class: "btn btn-lg btn-block btn-danger-override") %>
</div>
</div>
</div>
<% end %>
</div>
Now what I am trying to do is add a custom style to the 4th row element div
. (I added the erb syntax so you can see what I am talking about)
So, I added an array of CSS style classes to page_controller.rb :
@style = ["danger", "info", "success"]
Hoping there is a way to get the 4th row element div
:
<div class="panel panel-danger">
in the first iteration, then in the second iteration:
<div class="panel panel-info">
etc.
How can I do this?
source to share
Use each_with_index
to iterate over products and then use the index to get the appropriate style name:
<div class="row pricing-table">
<% @products.each_with_index do |p, p_index| %>
<div class="col-md-4">
<div class='panel <%= "panel-#{@style[p_index % @style.size]}" %>'>
<div class="panel-heading"><h3 class="text-center"><%= p.title %></h3></div>
<div class="panel-body text-center">
<p class="lead" style="font-size:40px"><strong><%= number_to_currency(p.price, precision: 0) %>/month</strong></p>
</div>
<ul class="list-group list-group-flush text-center list-no-bullets">
<%= p.description.html_safe %>
</ul>
<div class="panel-footer">
<%= link_to("Request Quote", "/quote_forms/new", class: "btn btn-lg btn-block btn-danger-override") %>
</div>
</div>
</div>
<% end %>
</div>
source to share