我工作的一个功能来搜索项目。预先加载仅结果的第一页与活动记录
我的模型是这样的,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的请求,然后手动合并的结果,但这是复杂的?
任何其他建议?