2014-02-18 11 views
0

在我看來,我有:如何檢測我的視圖中的第一次迭代? (軌道4)

<div class="item active"> 
    <%= image_tag "2.jpg",size: "500x300", class: "no-resize" %> 
    <div class="carousel-caption"> 
    Some tag. 
    </div> 
</div> 
<% @photos.each do |photo|%> 
<div class="item"> 
    <%= image_tag photo.attachment.url,size: "500x300",class: "no-resize" %> 
    <div class="carousel-caption"> 
    Some tag. 
    </div> 
</div> 
<% end %> 

有沒有實現這一點(因爲我提出的,是添加類「主動」第一張照片中唯一的變化)的乾燥方式,即我可以把循環中的第一項並檢測第一次迭代?

回答

11

嘗試each_with_index

<% @photos.each_with_index do |photo, i |%> 
<div class="item <%= "active" if i.zero? %>"> 
    <%= image_tag photo.attachment.url,size: "500x300",class: "no-resize" %> 
    <div class="carousel-caption"> 
    Some tag. 
    </div> 
</div> 
<% end %> 
1
['apple', 'orange', 'pear'].each_with_index do |fruit, index| 
    p "first is #{fruit}" if index == 0 
    p fruit 
end