I'm having trouble implementing a form on active admin where the second dropdown (subcategory) has to adjust to the category choice on the drop down that precedes it.
Basically I want to first set a industry for a company then select among sub-industry drop down. I have created 2 models:
- CompanySector
- CompanySubsector
For practical reasons, I use the words 'sector' and 'subsectors' in the code.
I am trying to use @okliv suggestions on Active Admin - refresh second drop down based on first drop down, Ruby on Rails but with no success.
1- I created a route
In #routes.rb
resources :companies
post '/change_company_subsectors' =>'company_sectors#change_company_subsectors'
2- I defined a define helper containing ajax request in Helpers/ApplicationHelper.rb
def remote_request(type, path, params={}, target_tag_id)
"$.#{type}('#{path}',
{#{params.collect { |p| "#{p[0]}: #{p[1]}" }.join(", ")}},
function(data) {$('##{target_tag_id}').html(data);}
);"
end
3- i put in admin/company.rb this method for :onchange action
controller do
def change_company_subsectors
@company_subsectors = CompanySector.find_by_id(params[:company_sector_id]).try(:company_subsectors)
render :text=>view_context.options_from_collection_for_select(@company_subsectors, :id)
end
end
4- And in my active amdin form admin/company.rb, i added this in the edit form:
form do |f|
f.inputs "company" do
f.input :company_sector_id, :input_html => {
:onchange => remote_request(:post, :change_company_subsectors, {:company_sector_id => "$('#company_sector_id').val()"}, :company_subsector_id)
}
f.input :company_subsector_id
end
But the results is very bad: I don't even see a dropdown populated with the Sectors and Subsectors possibilities.
I should see for Sectors: Leisure/Travel/Fashion... but I see nothing. And i see also nothing for SubSectors.
Shouldn't I use formtastic Collections like: :as => :select, :collection => CompanySubsector.all
?
Does anyone know where I have made mistakes?
First off I'd suggest against putting JS directly on an HTML element; it makes for much more difficult debugging later on.
Here's what I often do: