6

經過相當多的搜索後,我仍然有點失落。還有一些類似的問題涉及到對多個模型進行分頁處理,但是它們要麼沒有答案,要麼分別討論每個模型。如何分頁來自多個模型的記錄? (我是否需要一個多態連接?)

我需要一次對一個帳戶的所有記錄進行分頁。

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,應用程序沒有生產。

+0

使用will_paginate,th是應該幫助:http://stackoverflow.com/questions/1465949/how-to-use-will-paginate-with-a-nested-resource-in-rails –

+0

謝謝。但是,那不是我想要的。 – GoodGets

+0

認爲「通過一組數據行進行分頁」而不是分頁瀏覽一個數據庫表的多行可能會有所幫助。數據來自多少模型無關緊要。你也可以看看kaminiri,看看它是否更好地滿足你的需求。 –

回答

1

好問題......我不知道一個「好」的解決方案,但你可以做一個哈克之一紅寶石:

你需要首先提取出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) 

注:未經測試,可能會充滿bug ...;)

+0

謝謝你的回覆。但是,這太不可靠了,每次都需要獲取60條額外的記錄。然後不得不跟蹤每一個展示的數量。此外,您可以將things_array重構爲如下形式: '(電子郵件+任務+筆記).sort_by(&:updated_at).take(30)' – GoodGets

+0

需要反轉以獲取最新信息: '筆記).sort_by(&:updated_at).reverse.take(30)' – GoodGets

+0

是的 - 絕對不行的...正如我所說 - 只是一個哈克解決方案:) –

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%> 
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 

完蛋了... :)

相關問題