I have a Rails application in which I try to select a list of objects based on which region is selected on the form. So far I have implemented group_collection_select to do this, as well as a bit of CoffeeScript.
It works when creating a new record and choosing a region. The behavior is to show only the objects listed for the selected region. What does not work when editing a record, the choice of tools shows all the objects grouped by region, and not the restrictions of objects in the selected region.
If I select another area, and then select the original reason, a corresponding list of objects will appear.
I would like to learn how to reorganize CoffeeScript, where when editing an entry, the function starts both when the page loads (when editing) and when it changes.
Finally, there are cases where the transfer_from_id parameter is set to nil / blank, and we use a text field called transfer_from_other. Currently, if I do not select an object and do not fill out transfer_from_other, because CoffeeScript loads the objects in transfer_from_id, it will set transfer_from_id as the first object in the region. I would like to do this anywhere, if no object is selected, the value of transfer_from_id is zero, so I can use transfer_from_other.
This is 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' %> <%= f.label :Transfer_From_Other%> <%= f.text_field :transfer_from_other %>
If my question and examples are not clear, let me know and I will gladly edit it.