Rails Kitchen

It's a place to write on stuff I learned recently.

Autocomplete Using Chosen in Rails Active_admin

| Comments

In one of my recent project, I need to implement an autocomplete in active_admin interface to select one or more users from the 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.
1
gem ‘chosen-rails’
Once the gem is installed, include chosen javascript assets to your js file.
1
//= require chosen-jquery
In /app/admin/modelname.rb
1
2
3
4
5
6
7
8
9
10
ActiveAdmin.register Modlename do
  #Customize creates 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
1
2
3
$(document).ready(function(){
   $(".chosen-input").chosen();
});
if you are using coffee script instead of js then use this
1
2
3
4
5
$ ->
  # 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.
1
*= require chosen
To include more details check Here
Thats it, you will have a nice autocomplte with multiselect . Happy coding…

Comments

Lobna Mohamed
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??

Comments