Wednesday, January 1, 2014

Autocomplete using Chosen in Rails Active_admin

In one of my recent project, i need to implement a autocomplte in active_admin interface to select one or more users from user list. I tried googling on this and zeroed in on the library Chosen. Chosen by default supports multiple select, selected state.

Chosen is available as a gem for Ruby on Rails which fits well with Asset Pipeline.
Include Chosen gem in your Gemfile.

gem 'chosen-rails'

Once the gem is installed, include chosen javascript assets to your js file. 

//= require chosen-jquery

In /app/admin/modelname.rb

ActiveAdmin.register Modlename do
#Customize create and edit form
form do |f|
    f.inputs do
       f.input :name
       f.input :othermodel, :input_html => { :class => "chosen-input" } # other model with has_many relation ship
    end
  f.buttons
  end   
end  
in active_admin.js
$(document).ready(function(){
   $(".chosen-input").chosen();
});
if you are using coffee script instead of js then use this 
$ ->
  # enable chosen js
  $('.chosen-input').chosen
    allow_single_deselect: true
    no_results_text: 'No results matched'
Then, include Chosen stylesheet assets to your css file.
*= require chosen

To include more details check here 

Thats it, you will have a nice autocomplte with multiselect . Happy coding...

1 comment:

  1. Thanks for the good post, but does not save data to the database
    I guess it related to permit_params I am trying this
    permit_params :name, :othermodel_ids
    but still not working, have you another idea??

    ReplyDelete