如何使用提取的记录进行编号?

时间:2013-01-24 07:49:54

标签: ruby-on-rails ruby-on-rails-3 pagination kaminari

此代码提取10条最新记录

@comments = @topic.comment_threads.order("created_at DESC").page(params[:page]).per(10)

我想对获取的记录进行编号 因为它是desc顺序,它将是这样的

"Displaying comments 1 - 10 of 18 in total 

No. 18 Hi
No. 17 Hello
No. 16 Hola
No. 15 Howdy
No. 14 What's up
No. 13 Hi there
No. 12 Yo
No. 11 Oh
No. 10 Ah
No.  9 Eeeee

我怎样才能在视图中看到这个号码? 它应该像

<%= "No. " + ????????????? %>

2 个答案:

答案 0 :(得分:3)

使用 each_with_index

@comments.each_with_index.map {|comment, index| "No #{index} #{comment}"}

答案 1 :(得分:2)

UPDATE-2:

降序

<% params[:page] = params[:page].blank? ? 1 : params[:page]%>
<% total = @comments.total_count - ((params[:page].to_i-1)*10)+1 %>
<% @comments.each do |comment| %>
   <%= "No. #{total-=1} #{comment}" %>
<% end %>

升序

<% params[:page] = params[:page].blank? ? 1 : params[:page]%>
<% i = ((params[:page].to_i-1)*10)+1 %>
<% @comments.each do |comment| %>
   <%= "No. #{i+=1} #{comment}" %>
<% end %>