我工作的一個功能來搜索項目。預先加載僅結果的第一頁與活動記錄
我的模型是這樣的,roughtly:
User has many items
User has many addresses
User has one profile
Item has many images
Item has many addresses
Item belongs to category
我想顯示用戶分組的結果,例如:
Results for 'Laptop':
Items of Bob:
Laptop dell (details...)
Samsung laptop (details...)
Items of Alice:
Laptop HP (details...)
...
所以我有一個預先加載這個大查詢:
r = User.includes([{items: [:images, :addresses, :category]}, :addresses, :profile]).
joins(:items).
where('query like "%laptop%"').
where(...).
limit(80).
all
# then get the first page of results with kaminary
然後我用erb中的這樣一個循環顯示:
r.each do |u|
# items of user u
u.items do |i|
# item i
end
end
一切工作正常,除了預先加載需要時間looong。通過急於加載只有顯示的第一頁上的項目可能會快得多。
這是可能的活動記錄,以急於負載只記錄了條件?例如:User.includes([:table1, table2], conditions: 'users.id in (1,2,3)')
?
另一種解決辦法是執行與極限20大請求,然後重做不預先加載了極限80的請求,然後手動合併的結果,但這是複雜的?
任何其他建議?