We have two models
Book has_many :reviews
Review belongs_to :book
A Review has a rating (from 1 to 5).
book1
review1 - rating 5
review2 - rating 5
review3 - rating 4
book2
review4 - rating 5
book3
review5 - rating 5
Let say I need to filter all books that have a rating of 5 I would do something like:
@books = Book.includes(:reviews)
.where(reviews: { rating: 5 })
.page(params[:page]).per(3)
The issue is that I get the following
book1
review1 - rating 5
review2 - rating 5
book2
review4 - rating 5
This is not working and is breaking pagination as the @books.total_count is 2 not 3 (which is the triggering pagination as we require per(3)). How would you fix it ?
I would expect the query to render 3 Books with all the reviews matching the where clause
book1
review1 - rating 5
review2 - rating 5
book2
review4 - rating 5
book3
review5 - rating 5
Pagination can be fixed by using
This works as expected but is not performant as there is no limit applied to @books on the first query. I think this should be optimized by using manual pagination.