15
votes

I have a Category Model and a SubCategory Model and id like the SubCategory select input to refresh depending on the SubCategories that are associated to the specific Category I have selected.

form do |f|
    f.inputs do
        f.input :title
        f.input :category, as: :select, collection: Category.all, :input_html => { :class => 'chzn-select', :width => 'auto', "data-placeholder" => 'Click' }
        f.input :sub_category, as: :select, collection: SubCategory.all, :input_html => { :class => 'chzn-select', :width => 'auto', "data-placeholder" => 'Click' }
    end
    f.actions
end
3

3 Answers

18
votes

You can use dependent select for this purpose. Example is given here

Active Admin

ActiveAdmin.register CatalogsProduct do
  form do |f|
    f.inputs "Details" do
      f.input :product, :as => :select, :collection => Product.all.collect {|product| [product.name, product.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 {|catalog| [catalog.attr_name, catalog.id]} : []) 
    end
    f.actions
  end
end

Catalog 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 {|catalog| {:id => catalog.id, :name => catalog.attr_name} }
  end
end
0
votes
  1. You have to create a member action (method: GET, params: the id of the selected Category) in the ActiveAdmin Category model that returns the SubCategories (in json, for example) belongs to the selected Category:

    https://github.com/activeadmin/activeadmin/blob/master/docs/8-custom-actions.md#member-actions

  2. You have to use jQuery (for exmaple) with ajax, that populate the SubCategory select input when the Category select input has been changed:

    Populate Select box options on click with Javascript/Jquery with Json data https://forum.jquery.com/topic/best-practices-for-populating-selects-with-ajax

0
votes

you can do something like this to add specific selection

form do |f|
            f.inputs do
            f.input :category , :as => :select, collection: (['conversion','double-bar', 'fixed-hybrid','removal-bar-over-denture', 'surgical-guides'])
  
            end
            actions 
          end