在 Rails 3 问题中分页 [英] Paginate in Rails 3 issues
问题描述
我目前正在开发一个用 Rails 2 编写的 Reddit 克隆应用程序,我正在尝试使用 Rails 3 中的新功能加快速度.该应用程序非常简单,它有一个 Links 脚手架有 :url
、:description
、:points
和 :created_at
.该应用程序路由到 links#submissions
,您可以在其中查看所有提交的链接并提交新链接.
I'm currently working on a Reddit clone app that I had written in Rails 2 and I'm trying to bring it up to speed with new features in Rails 3. The app is very simple, it has a Links scaffold which has :url
, :description
, :points
, and :created_at
. The app routes to links#submissions
where you can view all submitted links and submit a new link as well.
在提交页面上显示链接时,我遇到了 Rails 2 中的 paginate
方法问题.我目前正在运行 Rails 3.2.3,我知道我需要在 Rails 3 中使用 gem will_paginate
(我已经包含在我的 Gemfile
中)但是每当我尝试拉起 localhost:3000
我收到这个错误信息:
I've run into a problem with the paginate
method in Rails 2 when displaying the links on the submissions page. I am currently running Rails 3.2.3 and I understand that I need to use the gem will_paginate
in Rails 3 (which I have included in my Gemfile
) but whenever I try to pull up localhost:3000
I get this error message:
NoMethodError in LinksController#submissions...
undefined method paginate for #<LinksController:0x00000102ff5f98>
特别是在 Links 控制器的第 90 行.
specifically on line 90 of the Links controller.
这是我在 LinksController.rb 中的内容(第 90-93 行).
Here is what I have in my LinksController.rb (lines 90-93).
@link_pages, @Links = paginate :links, :order => order, :per_page => 20
@header_text = case ordering
when 'hot' then 'Top rated submissions'
when 'new' then 'Latest submissions'
这不是在 Rails 3 中使用 paginate 的正确方法吗?
Is this not the correct way to use paginate in Rails 3?
推荐答案
对于 will_paginate
,你应该在你的控制器中使用这样的东西:
For will_paginate
, you should use something like this in your controller:
@links = Link.paginate(:page => params[:page], :per_page => 20)
在您看来,给定页面的链接将存储在 @links
实例变量中.您可以遍历该集合并显示链接.
In your view, the links for the given page will be stored in the @links
instance variable. You can iterate over that collection and display the links.
要显示到其他页面的链接(链接),您可以在视图中的某处使用它:
To show the links to other pages (of links), you use this somewhere in the view:
will_paginate @links
您可以在此处找到有关 will_paginate
的更多帮助:https://github.com/mislav/will_paginate
You can find more help for will_paginate
here: https://github.com/mislav/will_paginate
然而,对于 Rails 3,我更喜欢 kaminari
而不是 will_paginate
.它使用 Rails 3 范围.
However, for Rails 3, I prefer kaminari
instead of will_paginate
. It uses Rails 3 scopes.
在控制器中看起来是这样的:
It looks like this in the controller:
@links = Link.page(params[:page]).per(20)
在视图中:
paginate @links
您可以在此处阅读有关 kaminari
的更多信息:https://github.com/amatsuda/kaminari
You can read more about kaminari
here: https://github.com/amatsuda/kaminari
您也可以在 kaminari
上观看 Ryan 的 Railscast:http://railscasts.com/episodes/254-pagination-with-kaminari
Also you can watch Ryan's Railscast on kaminari
here: http://railscasts.com/episodes/254-pagination-with-kaminari
这篇关于在 Rails 3 问题中分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!