Skip to content

Instantly share code, notes, and snippets.

@greendog
Last active December 15, 2015 17:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save greendog/5296183 to your computer and use it in GitHub Desktop.
Save greendog/5296183 to your computer and use it in GitHub Desktop.
active_admin + jquery autocomplete
1. to Gemfile:
gem "rails3-jquery-autocomplete"
gem "jquery-ui-rails"
2. to active_admin.css.scss
@import "active_admin/mixins";
@import "active_admin/base";
@import "jquery.ui.all";
3. to active_admin.js.coffee
#= require active_admin/base
#= require jquery-ui
#= require jquery_ujs
#= require autocomplete-rails
4. to app/admin/users.rb
ActiveAdmin.register User do
# search by user email example
collection_action :autocomplete_user_email, :method => :get
controller do
autocomplete :user, :email, :class_name => 'User', :display_value => :email,
:column_name => 'email', :extra_data => [:username]
end
form do |f|
f.semantic_errors
f.inputs do
f.input :user, :required => true, :as => :autocomplete,
:input_html => {
:update_elements => {:id => "#user_id"},
:id => 'user_select',
:name => ""
},
:url => autocomplete_user_email_path
f.input :user_id, :as => :hidden
end
f.inputs "Products" do
f.has_many :products do |product|
product.semantic_errors
# search by product name example
# ActiveAdmin.register Product do
# collection_action :autocomplete_product_name, :method => :get
#
# controller do
# autocomplete :product, :name, :class_name => 'Product', :display_value => :name, :column_name => 'name'
# end
# end
# to User.rb model:
# attr_accessible :products_attributes, :product_ids
# has_many :products
# accepts_nested_attributes_for :products, :allow_destroy => true
if product.object.new_record?
product.input :name, :as => :autocomplete, :url => autocomplete_user_product_name_path,
# NEW_PRODUCT_RECORD - do not remove it! Must be as NEW_NAMESPASE::RAILS_MODEL_NAME_RECORD
:input_html => {:update_elements => {:id => "#user_products_attributes_NEW_SPREE::PRODUCT_RECORD_id"},
:name => "" }
else
product.form_buffers.last << content_tag(:li, f.template.link_to(product.object.name, f.template.product_path(product.object)))
product.input(:destroy, :as => :boolean,
:input_html => {
:name => "",
:onchange => <<-JS
var el = $("#user_products_attributes_#{f.object.products.index(product.object)}_id");
if(this.checked == true){
el.attr('name', "");
}
if(this.checked == false){
el.attr('name', 'user[product_ids][]');
}
JS
}, :label => "Remove product")
end
product.input :id, :as => :hidden, :input_html => {:name => "user[product_ids][]"}
product.form_buffers.last
end
f.form_buffers.last
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment