该应用有一个类别,类别有子类别和品牌。当用户选择类别时,请加载分类品牌和子类别。在创造形式中所有的好事。
= form_for @advert do |f|
- @advert.errors.full_messages.each do |msg|
div class='msg'
= msg
div class='form-group'
= f.label :category
= f.collection_select :category_id, Category.order(:id), :id, :title, { prompt: t("forms.selecte.choose-category")}
div class='form-group'
= f.label :subcategory
= f.grouped_collection_select :subcategory_id, Category.order(:id), :subcategories, :title, :id, :title,{ prompt: t("forms.selecte.choose-subcategory")}
div class='form-group'
= f.label :brand
= f.grouped_collection_select :brand_id, Category.order(:id), :brands, :title, :id, :title,{ prompt: t("forms.selecte.choose-brand")}
div class='form-group'
= f.label :title
= f.text_field :title, class: 'form-control'
div class='form-group'
= f.label :content
= f.text_area :content, size: '60x12', class: 'form-control'
= f.submit t('forms.buttons.submit')
ready = ->
jQuery ->
$('#advert_subcategory_id').parent().hide()
$('#advert_brand_id').parent().hide()
subcategories = $('#advert_subcategory_id').html()
brands = $('#advert_brand_id').html()
$('#advert_category_id').change ->
category = $('#advert_category_id :selected').text()
escaped_category = category.replace(/([ #;&,.+*~\':"!^$[\]()=>|\/@])/g, '\\$1')
options_subcategories = $(subcategories).filter("optgroup[label='#{escaped_category}']").html()
options_brand = $(brands).filter("optgroup[label='#{escaped_category}']").html()
if options_subcategories
$('#advert_subcategory_id').html(options_subcategories)
$('#advert_subcategory_id').parent().show()
else
$('#advert_subcategory_id').empty()
$('#advert_subcategory_id').parent().hide()
if options_brand
$('#advert_brand_id').html(options_brand)
$('#advert_brand_id').parent().show()
else
$('#advert_brand_id').empty()
$('#advert_brand_id').parent().hide()
但是在编辑形式中,代码不能正常工作。子类别和品牌未加载。要更改它们,用户必须更改类别。加载编辑表单时必须显示已选择的子类别和品牌。如何解决?
解决方案:
$(window).load ->
category = $('#advert_category_id :selected').text()
escaped_category = category.replace(/([ #;&,.+*~\':"!^$[\]()=>|\/@])/g, '\\$1')
options_subcategories = $(subcategories).filter("optgroup[label='#{escaped_category}']").html()
options_brand = $(brands).filter("optgroup[label='#{escaped_category}']").html()
if options_subcategories
$('#advert_subcategory_id').html(options_subcategories)
$('#advert_subcategory_id').parent().show()
else
$('#advert_subcategory_id').empty()
$('#advert_subcategory_id').parent().hide()
if options_brand
$('#advert_brand_id').html(options_brand)
$('#advert_brand_id').parent().show()
else
$('#advert_brand_id').empty()
$('#advert_brand_id').parent().hide()
代码重复但有效。
答案 0 :(得分:0)
我想问题的解决方案是http://andrewradev.com/2011/05/25/grouped-select-helper-methods-in-rails/ 希望它能帮助您解决问题