Bri*_*ian 71 pagination ruby-on-rails will-paginate
我想知道是否有人可以解释如何在一个对象数组上使用will_paginate?
例如,在我的网站上,我有一个意见部分,用户可以对意见进行评分.这是我写的一个方法来收集评价意见的用户:
def agree_list
list = OpinionRating.find_all_by_opinion_id(params[:id])
@agree_list = []
list.each do |r|
user = Profile.find(r.profile_id)
@agree_list << user
end
end
Run Code Online (Sandbox Code Playgroud)
谢谢
kei*_*ley 213
will_paginate 3.0旨在利用ActiveRecord::Relation
Rails 3 中的新功能,因此它paginate
默认只定义关系.它仍然可以使用数组,但你必须告诉rails要求该部分.
在您config/initializers
(我使用过will_paginate_array_fix.rb
)的文件中,添加此项
require 'will_paginate/array'
Run Code Online (Sandbox Code Playgroud)
然后你可以在数组上使用
my_array.paginate(:page => x, :per_page => y)
Run Code Online (Sandbox Code Playgroud)
你可以Array#from
用来模拟分页,但这里真正的问题是你根本不应该使用它Array
.
这就是ActiveRecord关联的用途.您应该仔细阅读该指南,如果您正在开发Rails应用程序,则需要了解许多有用的内容.
让我告诉你一个更好的做同样事情的方法:
class Profile < ActiveRecord::Base
has_many :opinion_ratings
has_many :opinions, :through => :opinion_ratings
end
class Opinion < ActiveRecord::Base
has_many :opinion_ratings
end
class OpinionRating < ActiveRecord::Base
belongs_to :opinion
belongs_to :profile
end
Run Code Online (Sandbox Code Playgroud)
重要的是您的数据库模式遵循正确的命名约定或所有这些都将中断.确保使用数据库迁移创建表而不是手动执行.
这些关联将在您的模型上创建帮助程序,以使搜索更容易.您可以使用named_scope
或scope
取决于您是否使用Rails 2.3或3.0,而不是迭代OpinionRating列表并手动收集用户.既然你没有指定,我会举两个例子.将此添加到您的OpinionRating类:
2.3
named_scope :for, lambda {|id|
{
:joins => :opinion,
:conditions => {
:opinion => { :id => id }
}
}
}
named_scope :agreed, :conditions => { :agree => true }
named_scope :with_profiles, :includes => :profile
Run Code Online (Sandbox Code Playgroud)
3.0
scope :agreed, where(:agree => true)
def self.for(id)
joins(:opinion).where(:opinion => { :id => id })
end
Run Code Online (Sandbox Code Playgroud)
在这两种情况下,你可以调用for(id)
的OpinionRatings
模型,并把它传递一个id:
2.3
@ratings = OpinionRating.agreed.for(params[:id]).with_profiles
@profiles = @ratings.collect(&:profile)
Run Code Online (Sandbox Code Playgroud)
3.0
@ratings = OpinionRating.agreed.for(params[:id]).includes(:profile)
@profiles = @ratings.collect(&:profile)
Run Code Online (Sandbox Code Playgroud)
所有这一切的结果是你现在可以轻松地分页:
@ratings = @ratings.paginate(:page => params[:page])
Run Code Online (Sandbox Code Playgroud)
Rails 4.x的更新:或多或少相同:
scope :agreed, ->{ where agreed: true }
def self.for(id)
joins(:opinion).where(opinion: { id: id })
end
Run Code Online (Sandbox Code Playgroud)
虽然对于较新的Rails,我的偏好是kaminari的分页:
@ratings = @ratings.page(params[:page])
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
46806 次 |
最近记录: |