链接到当前页面和上一页面不起作用

时间:2012-07-10 15:02:32

标签: ruby-on-rails-3.2

错误

undefined method `current' for nil:NilClass
Extracted source (around line #28):

 25: </tr>
 26: <% end %>
 27: </table>
 28: <%= link_to 'Previous page',{:page => @post_pages.current.previous } if    @post_pages.current.previous %>
 29: <%= link_to 'Next page',{:page => @post_pages.current.next } if @post_pages.current.next  %>
 30: <br />

控制器代码

  # GET /posts
  # GET /Posts.json
  def index
    @posts = Post.all

    respond_to do |format|
      format.html # index.html.erb
      format.json { render :json => @posts }
    end
  end

1 个答案:

答案 0 :(得分:1)

我建议使用will paginate gem,正如上述评论者之一所提到的那样。

然后你就像这样实现它(这些是来自gem页面的例子......):

## perform a paginated query:
@posts = Post.paginate(:page => params[:page])

# or, use an explicit "per page" limit:
Post.paginate(:page => params[:page], :per_page => 30)

## render page links in the view:
<%= will_paginate @posts %>

在您的具体示例中,它将是这样的:

def index
  @posts = Post.paginate(:page => params[:page])

  respond_to do |format|
    format.html # index.html.erb
    format.json { render :json => @posts }
  end
end

你的观点会更简单:

<%= will_paginate @posts %>

你需要完成一些细节,但它会让事情变得更容易。

以下是2个Railscasts,它们将为您提供一些背景信息:

http://railscasts.com/episodes/174-pagination-with-ajax/

http://railscasts.com/episodes/240-search-sort-paginate-with-ajax