我有一个 Rails 应用程序,我试图根据表单中选择的区域来选择设施列表。到目前为止,我已经实现了 group_collection_select 以及一些 CoffeeScript 来执行此操作。
它在创建新记录和选择区域时起作用。行为是仅显示为所选区域列出的设施。不起作用的是,在编辑记录时,选择设施会显示按区域分组的所有设施,而不是将设施限制在所选区域。
如果我选择另一个区域,然后选择原始原因,则会显示正确的设施列表。
我想了解如何将 CoffeeScript 重构为在编辑记录时在页面加载(编辑时)和更改时触发该函数的位置。
最后,在某些情况下,transfer_from_id 设置为 nil/blank,并且我们使用名为transfer_from_other 的文本字段。目前,如果我不选择设施并填写transfer_from_other,因为CoffeeScript在transfer_from_id中加载设施,它将通过范围内的第一个设施设置transfer_from_id。我想将其设置为如果未选择任何设施,则transfer_from_id为零,因此我可以使用transfer_from_other。
我的代码如下所示:
来电.js.咖啡
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()
区域.rb
has_many :facilities
设施.rb
attr_accessible :region_id
belongs_to :region
_form.html.erb 摘录
<%= 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 %>
如果我的问题和示例不清楚,请告诉我,我很乐意进行编辑。