In my view I have a simple form with two select lists:
<%= simple_form_for @job, url: jobs_path do |f| %>
<%= f.input_field :types, as: :select, collection: @types, id 'types-select' %>
<%= f.input_field :subtypes, as: :select, collection: @subtypes %>
<% end %>
When a user selects an option from the first list, the second list below should be populated with values from the database based on the above selection.
For this reason, I am making ajax request when a user selects an option from the first list:
$('#types-select').change(function(){
$.ajax({
url: '/subtypes',
dataType: 'json',
type: 'GET',
data: {
type_id: this.value
},
success: function(data) {
console.log(data);
}
});
});
Controller looks like this:
class SubtypesController < ApplicationController
respond_to :json
def index
@subtypes = Type.find(params[:type_id]).subtypes
render json: @subtypes
end
end
At this point how can I fill up the second select with options from @subtypes?