Skip to content

Instantly share code, notes, and snippets.

@Amitesh
Created November 23, 2011 20:57
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Amitesh/1389891 to your computer and use it in GitHub Desktop.
Save Amitesh/1389891 to your computer and use it in GitHub Desktop.
Problem with Kaminari pagination on Rails Active Record joins
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
@georgesve
Copy link

georgesve commented Nov 3, 2022

Let's say a Book has_many :reviews. Review have an attribute hidden: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 ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment