nul*_*tek 5 forms jquery activerecord coffeescript ruby-on-rails-3
我有一个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.
这是我的代码的样子:
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()
Run Code Online (Sandbox Code Playgroud)
region.rb
has_many :facilities
Run Code Online (Sandbox Code Playgroud)
facility.rb
attr_accessible :region_id
belongs_to :region
Run Code Online (Sandbox Code Playgroud)
_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 %>
Run Code Online (Sandbox Code Playgroud)
如果我的问题和示例不清楚,请告诉我,我将很乐意编辑.
关于更新页面加载和选择更改上的选择,除非我遗漏了某些东西不足以简单地将选择更新部分分解为它自己的函数,然后在页面加载时调用一次,然后在每个上面调用选择改变?
jQuery ->
facilities = $('#call_transfer_from_id').html()
update_facilities = ->
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()
$('#call_region_id').change ->
update_facilities()
update_facilities()
Run Code Online (Sandbox Code Playgroud)
关于第二部分,每次更新#call_transfer_from_id选择时,您将丢失空白选项.每次选择区域时,第二个版本都会添加并选择一个空白选项:
jQuery ->
facilities = $('#call_transfer_from_id').html()
update_facilities = ->
region = $('#call_region_id :selected').text()
options = $(facilities).filter("optgroup[label=#{region}]").html()
if options
# Set the options
$('#call_transfer_from_id').html(options)
# Add in a blank option at the top
$('#call_transfer_from_id').prepend("<option value=''></option>")
# Ensure that the blank option is selected
$('#call_transfer_from_id option:first').attr("selected", "selected");
else
$('#call_transfer_from_id').empty()
$('#call_region_id').change ->
update_facilities()
update_facilities()
Run Code Online (Sandbox Code Playgroud)