felipeecst
felipeecst

Reputation: 1415

Kaminari/Ransack - Sort and Pagination issue

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?

Upvotes: 0

Views: 977

Answers (1)

Pavling
Pavling

Reputation: 3963

You have some includes in your results, and each of those tables will presumably have a created_at field, so your sort could be ambiguous.

It's worth looking in the console at what SQL gets generated when you run this query, but you may find that changing your 'sorts' line to:

ransack.sorts = 'contacts.created_at desc' if ransack.sorts.empty? (or whatever table name is correct for you)

...helps to disambiguate the sorting.

Upvotes: 1

Related Questions