Reputation: 4797
I have a very basic architecture on my Ruby on Rails app:
a company model
a Industry model (a company belongs to an industry)
a Sub-industry model (a subindustry belongs to a Industry)
On my active admin form page, I want to put fields so that for each company, I first select in a drop down the industry it belongs to (this works so far), and then another field "sub industry", that would ONLY display, according to the industry I selected in the previous field, the subindustries that I have categorized previously in this industry.
For example, coca would go in industry "Drinks and beverage" and I'd like the form to dynamically adjust and only show in the field "sub indsutry" :a dropdown with "hot drinks", "cold drinks", "tea", "sodas"
form do |f|
f.inputs "Company" do
f.input :company_industry_id, :label => "Select industry:", :as => :select, :collection => CompanyIndustry.all
f.input :company_subindfustry_id, :label => "Select subindustry:", :as => :select, :collection => CompanySubindustry.all
end
Obviously I have a problem as so far, it show me ALL the subindustries I have and not only the subindustries WITHIN the industry I select on the previous field.
Does anyone know how I can solve that ?
Upvotes: 0
Views: 4019
Reputation: 1334
I chose to approach this in a quick and dirty, non AJAX fashion. It worked well for my scenario.
Note that the non-applicable items in the secondary select are disabled, not hidden. If you really need to hide them, I would clone & rebuild the select instead of disabling specific options.
#...
f.input :user, :input_html => {
##Manipulate Location select based on selected User
:onchange => "
var user = $(this).val();
$('#order_location_id').val(0).find('option').each(function(){
var $option = $(this),
isCorrectUser = ($option.attr('data-user') === user);
$option.prop('disabled',!isCorrectUser);
});
"
}
##Insert necessary Location info into DOM
f.input :location, collection: Location.all.map{ |loc|
[loc.name,loc.id, {"data-user" => loc.user_id}]
}
#...
Upvotes: 5