使用来自多个数组的属性对模型进行分页

时间:2013-05-31 08:32:23

标签: ruby-on-rails pagination will-paginate kaminari

我想要在分页表中一起显示四种类型的Rawscores。

代码如下:

@facebook_scores_today = Rawscore.where(:channel_string => "Facebook", :project => @project, :created_at.gt => Time.now.beginning_of_day)

@youtube_scores_today = Rawscore.where(:channel_string => "Youtube", :project => @project, :created_at.gt => Time.now.beginning_of_day)

@twitter_scores_today = Rawscore.where(:channel_string => "Twitter", :project => @project, :created_at.gt => Time.now.beginning_of_day)

@influence_scores_today = Rawscore.where(:channel_string => "Influence", :project => @project, :created_at.gt => Time.now.beginning_of_day)

其中Rawscore具有多个值的哈希值作为表的属性,具体取决于:channel_string

我应该怎么做?任何可以帮助“will_paginate”或“kaminari”的宝石?

更新(这是我的Rawscore模型)

class Rawscore
  include Mongoid::Document
  include Mongoid::Timestamps::Created #for created_at field

  belongs_to :channel
  belongs_to :project
  field :values, type: Hash
  validates :values, :presence => true

end

我想在Rawscore模型中显示:值Hash的键值。

2 个答案:

答案 0 :(得分:1)

Kaminari可以对数组进行分页,但效率不高,因为Active Record会实例化所有检索到的记录(即如果你有10000条记录并且只想显示100条,那么内存中将有10000个AR对象)

Kaminari.paginate_array(my_array_object).page(params[:page]).per(10)

相反,您可以考虑加入查询并使用查询分页

scores_today = Rawscore.where(
  :channel_string => ["Facebook", "Youtube", "Twitter", "Influence"], 
  :project => @project, :created_at.gt => Time.now.beginning_of_day
).page(params[:page])

答案 1 :(得分:0)

问题的答案在于使用WillPaginate :: Collection创建自己的分页结构。

这是rubydoc链接:http://rubydoc.info/github/mislav/will_paginate/frames