khalidh
khalidh

Reputation: 883

How to sort in pagination

Current code is showing results in random order but I want to display USA list first in order to India, UK and China.

@obj = User.where(:area => ["USA","India","UK","China"]).paginate(:page => params[:page], :per_page => 1)

I am using Paginate gem.

gem 'will_paginate', '~> 3.1.0'
gem 'will_paginate-bootstrap'

Upvotes: 1

Views: 368

Answers (2)

Dario Barrionuevo
Dario Barrionuevo

Reputation: 3257

You can achieve what you need by adding a simple CASE logic to your ordering, try this:

@collection = User
  .where(area: %w(USA India UK China))
  .order("CASE area WHEN 'USA' THEN 'a' WHEN 'India' THEN 'b' WHEN 'UK' THEN 'c' ELSE 'd' END")
  .paginate(page: params[:page], per_page: 1)

Given CASE syntax could vary according your RDBMS, you should check if you need to adjust something. Hope it helps.

Upvotes: 0

Eyeslandic
Eyeslandic

Reputation: 14890

You can use this sql trick to order by a predefined list.

@obj = User.where(area: %w(USA India UK China))
  .order("area = 'USA' desc")
  .order("area = 'India' desc")
  .order("area = 'UK' desc")
  .order("area = 'China' desc")
  .paginate(page: params[:page], per_page: 1)

Upvotes: 2

Related Questions