2012-10-13 52 views
5

我有一個項目列表,我在每個視圖中循環顯示。這完全沒問題。然而,我想要得到每個項目的數量,每個項目的增量都隨着每個循環而增加(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 %> 

回答

11

使用#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 %> 
+0

這肯定奏效!然而;有可能在1開始我?因爲我想用它作爲視覺編號。 – CaptainCarl

+2

你可以像這樣'<%= i+1 %>'增加1。這應該工作,但更多的信息看看[這裏](http://stackoverflow.com/questions/5646390/ruby-each-with-index-offset)。 –

+0

夠公平,謝謝! – CaptainCarl

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

任何你想要的循環內的代碼。

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的。如果使用部分渲染集合,則「object」是您的模型名稱的對象將具有object_counter變量。例如:

<%= render @trip.triplocations %> 

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