简体   繁体   English

迭代rails对象和数组

[英]Iterate over rails object and array

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. 我正在迭代一个模型对象@products(目前在DB中有3个),但我还需要对我视图中返回的每个对象应用不同的样式。

Here is my current code in my page_controller.rb to get only the first 3 products: 这是我在page_controller.rb中的当前代码,仅获取前3个产品:

@products = Product.where(id: 1..3)

In my view index.html.erb : 在我看来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. 现在,我要做的是为第4行div元素添加自定义样式。 (I've put in erb syntax so you can see where I'm talking about) (我已经输入了erb语法,所以你可以看到我在说什么)

So, I added an array of the CSS style classes to page_controller.rb : 所以,我在page_controller.rb中添加了一个CSS样式类数组:

@style = ["danger", "info", "success"]

In hopes that there is a way to get the 4th line div element to be: 希望有一种方法可以获得第4行div元素:

<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? 我怎么能这样做?

Use each_with_index to iterate over products and then use the index to get the corresponding style name: 使用each_with_index迭代产品,然后使用索引获取相应的样式名称:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM