如何从多个模型中分页记录?(我需要多态连接吗?)

Goo*_*ets 7 ruby-on-rails will-paginate ruby-on-rails-3 kaminari ruby-on-rails-3.1

经过相当多的搜索,我仍然有点迷失.还有一些其他类似的问题涉及对多个模型进行分页,但它们要么没有答案,要么分别对每个模型进行讨论.

我需要立刻对帐户的所有记录进行分页.

class Account
  :has_many :emails
  :has_many :tasks
  :has_many :notes
end
Run Code Online (Sandbox Code Playgroud)

所以,无论它们是什么,我都想找到30个最新的"东西".目前的分页解决方案是否可以实现这一目标?

喜欢使用一些渴望加载和Kaminari或will_paginate的组合?


或者,我应该首先设置所有这些东西的多态连接,称为Items.然后对最近的30个项目进行分页,然后查找这些项目的相关记录.

如果是这样,我不确定该代码应该是什么样子.有什么建议?


哪种方式更好?(甚至可能)

Rails 3.1,Ruby 1.9.2,app尚未投入生产.

Tar*_*ast 1

好问题......我不确定是否有一个“好的”解决方案,但你可以用 ruby​​ 做一个 hacky 的解决方案:

您需要首先取出每种类型“事物”中最新的 30 个,并将它们放入一个数组中,按created_at 索引,然后按created_at 对该数组进行排序,并取出前 30 个。

完全不重构的开始可能是这样的:

emails = Account.emails.all(:limit => 30, :order => :created_at)
tasks = Account.tasks.all(:limit => 30, :order => :created_at)
notes = Account.notes.all(:limit => 30, :order => :created_at)
thing_array = (emails + tasks + notes).map {|thing| [thing.created_at, thing] }
# sort by the first item of each array (== the date)
thing_array_sorted = thing_array.sort_by {|a,b| a[0] <=> b[0] }
# then just grab the top thirty
things_to_show = thing_array_sorted.slice(0,30)
Run Code Online (Sandbox Code Playgroud)

注意:未经测试,可能充满错误......;)