select2 ajax

gem

gem "select2-rails"
gem 'ransack'

html

= form_for @content, url: club_contents_path(params[:club_access_token]) do |f|
  .form-group
    = f.label '部長'
    .select
      - if params["leader_employee_id"]
        = select_tag 'leader_employee_id', options_for_select(@employees.collect{ |u| [u.profile, u.id] }, selected: params["leader_employee_id"]), { class: 'chosen-select form-control', multiple: false, prompt: "名前か従業員番号を入力して、検索してください" }

js

contents.coffee

$ ->
  $('.chosen-select').select2({
    placeholder: "名前か従業員番号を入力して、検索してください"
    ajax:
      url: '/employees/search.json'
      dataType: 'json'
      delay: 250
      cache: false
      data: (params) ->
        q: params.term
      processResults: (data, params) ->
        results: $.map data, (obj)->
          id: obj.id
          text: obj.name
  })

root

get 'employees/search' => 'employees#search'

コントローラー

class EmployeesController < ApplicationController
  def search
    q = params[:q]
    if q.blank?
      @employees = nil
    else
      @employees = Employee.search(:name_cont=>q).result
    end
    render json: @employees
  end
end

参考

https://select2.github.io/examples.html
http://blog.scimpr.com/2016/01/04/rails4-2%E3%81%A7select%E3%82%92%E7%B5%9E%E8%BE%BC%E3%81%A7%E3%81%8D%E3%82%8Bselect2%E3%82%92%E4%BD%BF%E3%81%A3%E3%81%A6%E3%81%BF%E3%81%9F%E3%80%9Cselect2/