7

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

我需要一次对帐户的所有记录进行分页。

class Account
  :has_many :emails
  :has_many :tasks
  :has_many :notes
end

所以,我想找到最近的 30 个“事物”,无论它们是什么。这甚至可以使用当前的分页解决方案吗?

喜欢使用急切加载和 Kaminari 或 will_paginate 的某种组合?


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

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


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

Rails 3.1、Ruby 1.9.2、应用程序未投入生产。

4

3 回答 3

2

与 will_paginate :

@records = #do your work and fetch array of records you want to paginate ( various types )

然后执行以下操作:

current_page = params[:page] || 1
per_page = 10
@records = WillPaginate::Collection.create(current_page, per_page, records.size) do   |pager|
pager.replace(@records)
end

那么在你看来:

<%=will_paginate @records%>
于 2013-03-11T11:11:54.017 回答
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)

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

于 2011-11-03T18:57:56.913 回答
0
emails = account.emails
tasks = account.tasks
notes = account.notes

@records = [emails + tasks + notes].flatten.sort_by(&:updated_at).reverse

@records = WillPaginate::Collection.create(params[:page] || 1, 30, @records.size) do |pager|
  pager.replace(@records)
end

而已... :)

于 2015-10-16T14:00:50.707 回答