2

此代码获取 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. " + ????????????? %>
4

2 回答 2

3

采用each_with_index

@comments.each_with_index.map {|comment, index| "No #{index} #{comment}"}
于 2013-01-24T07:53:41.337 回答
2

更新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 %>
于 2013-01-24T08:25:36.633 回答