Question

I'm working on implementing autocomplete utilizing Select2 to get an AJAX loaded list of Users from JSON in order to fill a multi-value select box.

So far I've been able to implement most of the desired functionality by referencing the following sources:

http://gistflow.com/posts/428-autocomplete-with-rails-and-select2

http://luksurious.me/?p=46

My problem is that, the autocomplete query is case sensitive. I need it to be case-insensitive. Through a bit of research, I came across a GitHub issue where the Select2 creator explains that "Ajax matching should be done on server side."

https://github.com/ivaynberg/select2/issues/884

After much trial and error and some extensive research, I've come up with no solutions to solve the case-sensitivity issue. Unfortunately, "matching on the server side" is a bit over my head, and I was wondering if somebody might be able to suggest a solution to this problem?

What follows is my work so far:

Haml

= hidden_field :recipient_id, "", data: { source: users_path }, class: "select2-autocomplete"

CoffeeScript

 $ ->

   $('.select2-autocomplete').each (i, e) ->
     select = $(e)
     options = { 
       multiple: true 
     }

     options.ajax =
       url: select.data('source')
       dataType: 'json'
       data: (term, page) ->
         q: term
         page: page
         per: 5

       results: (data, page) ->
         results: data

     options.dropdownCssClass = 'bigdrop'
     select.select2 options

Users Controller

class UsersController < ApplicationController
  def index

    @users = User.order('name').finder(params[:q]).page(params[:page]).per(params[:per])

    respond_to do |format|
      format.html
      format.json { render json: @users }
    end

  end
end

User Model

class User < ActiveRecord::Base
  scope :finder, lambda { |q| where("name like :q", q: "%#{q}%") }

  def as_json(options)
    { id: id, text: name }
  end
end
Était-ce utile?

La solution

Figured it out!

The answer lies in the custom scope and the LIKE clause in the query. LIKE is a case-sensitive clause. Since, I'm using PostgreSQL, I was able to change the LIKE clause to ILIKE which is case-insensitive.

So in order to get case-insensitive matching, the User Model should look like the following:

User Model

class User < ActiveRecord::Base
  scope :finder, lambda { |q| where("name ILIKE :q", q: "%#{q}%") }

  def as_json(options)
    { id: id, text: name }
  end
end
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top