Html 迭代rails对象和数组
我正在迭代一个model object@products(目前数据库中有3个),但我还需要对视图中返回的每个对象应用不同的样式 以下是我在mypage_controller.rb中的当前代码,仅获取前3种产品:Html 迭代rails对象和数组,html,css,ruby-on-rails,ruby,ruby-on-rails-4,Html,Css,Ruby On Rails,Ruby,Ruby On Rails 4,我正在迭代一个model object@products(目前数据库中有3个),但我还需要对视图中返回的每个对象应用不同的样式 以下是我在mypage_controller.rb中的当前代码,仅获取前3种产品: @products = Product.where(id: 1..3) 在我看来index.html.erb: <div class="row pricing-table"> <% @products.each do |p| %> <div c
@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>
@style = ["danger", "info", "success"]
希望有办法将第四行div
元素设置为:
<div class="panel panel-danger">
在第一次迭代中,然后在第二次迭代中:
<div class="panel panel-info">
等等
如何才能做到这一点?使用
每个带有索引的\u来迭代产品,然后使用索引来获得相应的样式名称:
<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>
/month
如果@products.size
大于@style.size
,@style[p\u index]
将返回nil
。。。在这种情况下需要使用模:@style[p_index%@style.size]
编辑了我的答案。那是@Yoshijiawesome先生!谢谢你的团队合作!工作起来很有魅力,我学到了一些新东西:。实际上,我只需要从数据库中获取这个特定页面的前3个。