在View Rails中计数

Cap*_*arl 6 ruby each ruby-on-rails count ruby-on-rails-3

我有一个项目列表,我在我的节目视图中循环.这一切都很好.但是,我想得到每个项目前面的数字,每个循环递增(i = 0,i ++你知道钻孔).

现在,我怎么能在Rails中做到这一点?这就是我现在所得到的:

<% i = 0 %>
<% @trip.triplocations.each do |tl| %>
  <article id="<%= dom_id(tl)  %>">
    <strong> <%= tl.title %> </strong>
      <p>
        <%= tl.description %>
      </p>
  </article>
<% end %>
Run Code Online (Sandbox Code Playgroud)

wal*_*.ar 13

使用#each_with_index而不是在视图中实例化变量!

<% @trip.triplocations.each_with_index do |tl, i| %>
  <article id="<%= dom_id(tl) %>">
    <strong> <%= i %>. <%= tl.title %> </strong>
      <p>
        <%= tl.description %>
      </p>
  </article>
<% end %>
Run Code Online (Sandbox Code Playgroud)

  • 你可以像这样`<%= i + 1%>`增加1.这应该有效,但有关更多信息,请查看[HERE](http://stackoverflow.com/questions/5646390/ruby-each-with-index-offset). (3认同)