在Ruby on Rails中为index.html.erb添加分页 - 简单问题

bga*_*oci 4 ruby blogs pagination ruby-on-rails

我是新手,所以很容易.我已经建立了我的第一个博客,并希望将其设置为<%post.each do | post | %>帖子的渲染,我希望它工作,它只显示10个帖子,然后有一个链接,以查看下一个10.

我希望这是一个简单的问题.如果您希望我发布任何代码,请告诉我.

bra*_*fck 7

你应该使用gem will_paginate.

安装和使用非常简单:http://wiki.github.com/mislav/will_paginate/installation

用法示例:http://github.com/mislav/will_paginate


mmr*_*ins 7

will_paginate肯定是要走的路,我只是想我会添加一个链接到railscasts will_paginate视频,告诉你如何使用它,因为有时这可以比学习阅读文档更容易学习基础知识.另外,您将学习关于如何在Rails包含的部分中进行分页的简短历史(它更慢且更麻烦).旧的经典分页也被移植到它自己的插件中,但只有当你将Rails升级到他们把它拿出来的版本时才推荐使用它.

Railscasts有很多其他很棒的视频,你可能会觉得有用.例如,一旦你获得更高级,你可能想尝试ajax分页


Sim*_*tti 5

查看will_paginate宝石。

在 ActiveRecord 模型上进行分页非常容易:

@posts = Post.paginate :page => params[:page], :order => 'created_at DESC'
Run Code Online (Sandbox Code Playgroud)

在视图中,可以使用单个视图助手呈现页面链接:

<%= will_paginate @posts %>
Run Code Online (Sandbox Code Playgroud)


Iva*_*roz 5

我在使用“will_paginate”时遇到问题,安装 GEM 然后卸载……一个真正的问题!所以我决定在 RoR 上编写分页程序,这并不难,所以我想分享我所做的:

控制器:

  def index
#how many register per page i want to show
    @b = 30 
#params via GET from URL
    a = params[:page].to_i
#first register per page
    a1 = params[:page].to_i * @b
#the query can be easy...
    @callcenters = Income.all(:joins => "LEFT JOIN radcheck ON radcheck.id = incomes.radcheck_id", :order => "created_at DESC",:limit => "#{a1},#{@b}", :select => "radcheck.username as clave,caller_id, created_at, value")
#I need to know how many pages somehow
     @registrostotales = Income.all(:joins => "LEFT JOIN radcheck ON radcheck.id = incomes.radcheck_id", :select => "radcheck.username as clave,caller_id, created_at, value").count

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @callcenters }
    end
  end
Run Code Online (Sandbox Code Playgroud)

看法:

...
Total de registros: <%= numero = @registrostotales %><br/><br/>
<!-- total pages -->
<% pages = @registrostotales / @b %>
<!-- the last page -->
<% if pages % @b > 0 %><% pages = pages + 1 %><% end %>

Paginas:
<% (0..(pages-1)).each do |i| %>
<!-- href or link_to, http://xxxxxxxx/yyyy?page=i -->
  <%= link_to i+1, :action => "index", :controller => "callcenters", :page => i %>
<% end %>


<!-- the view.. -->
<table>
  <tr>
    <th>#</th>
    <th>Tel&eacute;fono (ID)</th>
    <th>Zona</th>
  </tr>

<% @callcenters.each do |callcenter| %>
  <tr>
    <td><%= numero - params[:page].to_i * 30 %><% numero = numero  - 1 %></td>
    <td><%= callcenter.caller_id %></td>
    <td><%= Node.first(:conditions => {:calling_id => callcenter.caller_id}).description %></td>
  </tr>
<% end %>
</table>
Run Code Online (Sandbox Code Playgroud)

我希望这对某人有所帮助!