2015-04-30 56 views
3

我遍歷模型對象@products(當前在數據庫中爲3),但我也需要對我的視圖中返回的每個對象應用不同的樣式。遍歷Rails對象和數組

這裏是我的page_controller.rb我當前的代碼只得到第3種款產品:

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

在我看來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> 

現在,我想要做的是將自定義樣式添加到第4行div元素。 (我已經把ERB語法,所以你可以看到我在談論)

所以,我加了CSS樣式類的數組來page_controller.rb

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

在希望有一種方式來獲得4號線div元素是:

<div class="panel panel-danger"> 

在第一次迭代,然後在第二次迭代:

<div class="panel panel-info"> 

等等。

我該如何做到這一點?

+0

是指出。我實際上只需要從我的數據庫中獲得這個特定頁面的前3個。 – Godzilla74

回答

3

使用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> 
+2

如果'@ products.size'大於'@ style.size','@style [p_index]'將返回'nil' ...您需要在這種情況下使用模數:'@style [p_index%@style .size]' – MrYoshiji

+0

編輯我的答案。那是@MrYoshiji – Adnan

+0

太棒了!感謝團隊合作!像魅力一樣工作,我學到了一些新東西:'.each_with_index' – Godzilla74