I am working on a feature to search for items.
My model is this, 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
I want to display the results grouped by user, eg:
Results for 'Laptop':
Items of Bob:
Laptop dell (details...)
Samsung laptop (details...)
Items of Alice:
Laptop HP (details...)
...
So I have this big query with eager loading:
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
And then I display with a loop like this in erb:
r.each do |u|
# items of user u
u.items do |i|
# item i
end
end
Everything works fine, except that the eager loading takes a looong time. It could be much faster by eager loading only the items on the first page that are displayed.
It is possible with active record to eager load only records with a condition ? Something like: User.includes([:table1, table2], conditions: 'users.id in (1,2,3)')
?
Another solution would be to execute the big request with a limit 20, and then redo the request without eager loading with a limit 80, and then manually merge the results, but this is complicated ?
Any other suggestions ?