I have a Rails app where I'm trying to select a list of facilities based on what region is selected in a form. So far, I've implemented group_collection_select to do this as well as a bit of CoffeeScript.
It works when creating a new record and selecting a region. The behavior being to only show facilities listed for the selected region. What does not work is when editing a record, selecting the facilities shows all of the facilities grouped by region instead of constraining the facilities to the selected region.
If I select another region and then select the original reason, the proper list of facilities show up.
I'd like to learn how to refactor the CoffeeScript to where when editing the record the function is fired both on load and on change.
Here's what my code looks like:
calls.js.coffee
jQuery ->
facilities = $('#call_transfer_from_id').html()
$('#call_region_id').change ->
region = $('#call_region_id :selected').text()
options = $(facilities).filter("optgroup[label=#{region}]").html()
if options
$('#call_transfer_from_id').html(options)
else
$('#call_transfer_from_id').empty()
region.rb
has_many :facilities
facility.rb
attr_accessible :region_id
belongs_to :region
_form.html.erb excerpt
<%= f.label :region %>
<%= f.collection_select(:region_id, Region.all, :id, :area, {:include_blank => true}, {:class => 'select', required: true}) %>
<%= f.label :Transfer_From %>
<%= f.grouped_collection_select :transfer_from_id, Region.order(:area), :active_facilities, :area, :id, :facility_name, {include_blank: true}, class: 'select' %>
If my question and examples are not clear, please let me know and I'll be happy to edit.