- Published on
- • 1 min read
Implement Dependent select in Active Admin
- Authors

- Name
- Shaiju Edakulangara
- @eshaiju
In a previous project, I needed to populate product catalogs in a second select box based on the product selected in the first select box within an ActiveAdmin form. I implemented this using the approach from @abhidsm's dependent-select repository.
Implementation
First, add the dependent_select.js file to your assets.
Now, add the logic to your ActiveAdmin resource file (e.g., catalogs_product.rb):
ActiveAdmin.register CatalogsProduct do
form do |f|
f.inputs "Details" do
f.input :product, :as => :select, :collection => Product.all.collect {|p| [p.name, p.id] }
f.input :catalog, :as => :select,
:input_html => {
'data-option-dependent' => true,
'data-option-url' => '/products/:catalogs_product_product_id/catalogs',
'data-option-observed' => 'catalogs_product_product_id'
},
:collection => (resource.product ? resource.product.category.catalogs.collect {|c| [c.attr_name, c.id]} : [])
end
f.actions
end
end
data-option-dependent: Binds the JS to the field.data-option-observed: Specifies the field to watch for changes.data-option-url: The URL to fetch data from.
Backend Controller
Add an index method with JSON output to the catalogs controller:
class CatalogsController < ApplicationController
respond_to :json
def index
if params[:product_id]
product = Product.find_by_id(params[:product_id])
@catalogs = product.category.catalogs
else
@catalogs = Catalog.all
end
render :json => @catalogs.collect {|c| {:id => c.id, :name => c.attr_name} }
end
end
Routes configuration:
resources :products do
resources :catalogs
end