I'm using Ransack, Kaminari and Postgres to perform queries/pagination inside my Rails controllers, and I have the following code:
ransack = current_user.condition? ? @company.contacts.ransack(params[:q]) :
current_user.contacts.ransack(params[:q])
ransack.sorts = 'id desc' if ransack.sorts.empty?
contacts = ransack.result.includes(:table1, :table2)
contacts = contacts.page(params[:page]).per(params[:per])
render json: contacts,
meta: pagination(contacts, total_count: true)
The pagination method is defined as follow:
def pagination(kaminari, total_count: false)
return unless kaminari.respond_to?(:current_page)
pagination = {
current_page: kaminari.current_page,
next_page: kaminari.next_page,
prev_page: kaminari.prev_page
}
pagination[:total_count] = kaminari.total_count if total_count
pagination
end
With this code, everything work as expected. However, if I change the sorts line to:
ransack.sorts = 'created_at desc' if ransack.sorts.empty?
Then I start to receive duplicate and unwanted entries in my results. Can anyone tell me why could this be happening?