This work for me on dependend "select" on Rails 6.0.4
Models
class Organization < ApplicationRecord
belongs_to :sector
belongs_to :sub_sectors
end
class Sector < ApplicationRecord
has_many :sub_sectors
end
class SubSector < ApplicationRecord
belongs_to :sector
end
Active admin form
ActiveAdmin.register Organization do
form do |f|
f.inputs "Details" do
f.input :sector, as: :select, collection: Sector.all
f.input :sub_sector_id, as: :select, collection: ([]) # The input is initialized without values
end
f.actions
end
end
You must do the following:
Create a controller, that returns the subsectors.
class SubSectorsController < ApplicationController
def sub_sectors_filter
if params[:sector_id]
sector = Sector.find(params[:sector_id])
@sub_sectors = sector.sub_sectors
else
@sub_sectors = []
end
render :json => @sub_sectors.collect {|sub_sector| {:id => sub_sector.id, :name => sub_sector.name} }
end
end
Add the route in the routes.rb
file.
get 'sub_sectors_filter/' => 'sub_sectors#sub_sectors_filter'
Inspect with your web browser console your selects, and use a CSS selector to create a jQuery object for the sector select, something like:
$('#organization_sector_id')
Add this block of code in the file /app/assets/javascripts/active_admin.js
, which is responsible for making the call to the generated controller, and adding the options that it returns.
//= require active_admin/base
$(function () {
$('#organization_sector_id').on('change', function () {
$('#organization_sub_sector_id option').remove(); // Remove all <option> child tags.
$.getJSON(`/sub_sectors_filter`, {sector_id: $(this).val()}, function(result){ // Documentation on getJSON: http://api.jquery.com/jQuery.getJSON/
$.each(result, function (i, item) { // Iterates through a collection
$('#organization_sub_sector_id').append($('<option>', { // Append an object to the inside of the select box
value: item.id,
text : item.name
}));
});
});
})
})
References:
Can't find the error in my dependent select drop down on Active Admin( Rails 3.2, Active Admin 1.0)
Populate Select box options on click with Javascript/Jquery with Json data