Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ransack gem - Case insensitive sort (Rails 4)

Using the Ransack gem, I'm trying to sort a simple list on an index page. However, there are both uppercase and lowercase values in the sort field name. To make them sorted useful, the sort should be case insensitive.

This is the model Vendor:

name:string, email:string, address:string, phone:string, fax:string

This is the controller:

class VendorsController < ApplicationController

def index
  @search = Vendor.search(params[:q])
  @vendors = @search.result
end

And the view:

/index.html.slim
tr
  th = sort_link @search, :name, "Name"
  th = sort_link @search, :email, "Company Email"
  th = sort_link @search, :address, "Address"

Any advice would be greatly appreciated.

like image 901
Luke Avatar asked Oct 30 '25 19:10

Luke


1 Answers

What you're looking for is a custom "Ransacker":

class Vendor < ActiveRecord::Base

    ransacker :name_case_insensitive, type: :string do
      arel_table[:name].lower
    end

end

view:

th = sort_link(@q, :name_case_insensitive)
like image 175
mutexkid Avatar answered Nov 02 '25 17:11

mutexkid