Reputation: 2512
I'm iterating over a model object @products (currently 3 in the DB), but I also need to apply different styling 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 view 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'm trying to do is add a custom style to the 4th line div
element. (I've put in erb syntax so you can see where I'm talking about)
So, I added an array of the CSS style classes to page_controller.rb:
@style = ["danger", "info", "success"]
In hopes that there is a way to get the 4th line div
element to be:
<div class="panel panel-danger">
in the first iteration, then in the second iteration:
<div class="panel panel-info">
and so on.
How would I be able to do this?
Upvotes: 3
Views: 1191
Reputation: 2967
Use each_with_index
to iterate over products and then use the index to get the corresponding 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>
Upvotes: 3