Created
November 23, 2011 20:57
-
-
Save Amitesh/1389891 to your computer and use it in GitHub Desktop.
Problem with Kaminari pagination on Rails Active Record joins
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Error Type : 1. Use "includes" instead of "joins" with kaminari pagination. | |
example : | |
books = Book.joins( :other_category ).where(['books.published_on is not null and other_categories.name like ?', "%#{category_name}%"]).order('books.title').page( page ).per( per ) | |
it makes sql for counting the record as : | |
SELECT COUNT(*) FROM `books` WHERE ( books.id IN (SELECT DISTINCT other_categories.book_id FROM other_categories WHERE other_categories.name LIKE '%Fiction%')) LIMIT 10 OFFSET 20 | |
This sql failed to return the count dues to limit and offset. | |
Use include instead of joins. | |
books = Book.includes( :other_category ).where(['books.published_on is not null and other_categories.name like ?', "%#{category_name}%"]).order('books.title').page( page ).per( per ) | |
It works perfectly with kaminari | |
==================== | |
Error Type : 2. Use model.all to pagination on second page when query has complex where clause | |
books = Book.where(['books.title LIKE ? | |
OR books.id IN (SELECT books_isbns.id | |
FROM books_isbns | |
WHERE books_isbns.isbn = ? | |
UNION | |
SELECT DISTINCT books_authors.book_id | |
FROM books_authors | |
WHERE books_authors.id IN (SELECT authors.id | |
FROM authors | |
WHERE authors.name LIKE ?) | |
)' , "%#{query}%", query, "%#{query}%"]).page( page ).per( per ) | |
books.all # to solve the pagination |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Let's say a Book
has_many :reviews
. Review have an attributehidden:boolean
The pagination breaks when we do a where on the has_many association like this:
books = Book.includes(:reviews).where(reviews: {hidden: true}).page(page).per(X)
The pagination limit occurs on the Reviews and not on the Book resulting in breaking pagination in case multiple reviews are attached to a Book. How would you fix this ?