在View Rails中计数

时间:2012-10-13 06:00:17

标签: ruby-on-rails ruby ruby-on-rails-3 count each

我的节目视图中有一个我正在循环的项目列表。这一切都很好。但是,我希望得到每个项目前面的数字,每个循环都会递增(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 %>

3 个答案:

答案 0 :(得分: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 %>

答案 1 :(得分:0)

可能你想要这种代码。

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

        </p>
    </article>
    <% i = i + 1 %> 
<% end %>

注意:

您可以放置​​代码

<%= i %>

你想在循环中的任何地方。

答案 2 :(得分:0)

Ruby中没有++运算符。而是使用+= 1

array = 'a'..'d'

i = 0
array.each do |element|
  puts "#{i} #{element}"
  i += 1
end

打印

0 a
1 b
2 c
3 d

但是,你不应该这样做,因为已经有一个方便的方法:

array = 'a'..'d'

array.each_with_index do |element, i|
  puts "#{i} #{element}"
end

还有另一种方法可以针对Rails执行此操作。如果使用partial来渲染集合,则可以使用object_counter变量,其中“object”是您的模型名称。例如:

<%= render @trip.triplocations %>

<% # in views/triplocations/_triplocation.html.erb %>
<%= triplocation_counter %>
<%= triplocation.title %>