Rails 3:Will_paginate的.paginate不起作用

时间:2011-07-13 06:15:06

标签: ruby-on-rails-3 will-paginate

我正在使用带有will_paginate的新手Rails 3版本。

@videos = user.youtube_videos.sort.paginate :page => page

我还将@@per_page属性添加到了我的youtube_video-model。

但它不会对它进行分页。我总是得到列出的集合中的所有项目。

我做错了什么?

你的,乔恩。

2 个答案:

答案 0 :(得分:2)

你为什么在这里打sort?这似乎是不必要的,并且可能会导致它找到所有视频并在其上调用分页,而不是关注Video模型中定义的任何变量。相反,可以使用范围将排序逻辑移动到Video模型中,或使用order方法。

答案 1 :(得分:1)

这是我的解决方案,我自己的答案,因为所有其他人在使用will_paginate并阅读此问题时遇到了问题:

创建一个这样的ApplicationController方法:

def paginate_collection(collection, page, per_page)
  page_results = WillPaginate::Collection.create(page, per_page, collection.length) do |pager|
    pager.replace(collection)
  end
  collection = collection[(page - 1) * per_page, per_page]
  yield collection, page_results
end

然后在你的Controller中,你得到了应该分页的集合:

page = setup_page(params[:page]) # see below
@messages = Message.inbox(account)
paginate_collection(@messages, page, Message.per_page) do |collection, page_results|
  @messages = collection
  @page_results = page_results
end

在你的观点中:

<% @messages.each do |message| %>
  <%# iterate and show message titles or whatever %>
<% end %>
<%= will_paginate @page_results %>

要定义page变量,请检查:

def setup_page(page)
  if !page.nil?
    page.to_i
  else
    1
  end
end

所以page = setup_page(params[:page])使用这个简单的方法就可以了。


这个工作!