以前我在f.select中创建了多个选择,使用
<%= f.select(:TYPE, Category.all.collect {|p| [ p.name, p.id ] },
{ :prompt => "Please select"},
{ :multiple => true, :size => 5 }) %>
它工作正常。
现在类别有自己的子项,需要为给定的类别选择子项。我尽力实施但无法取得成功。
@category = Category.all.collect {|p| [ p.name, p.id ] }
@subcategory = Category.first.subcategories.collect {|p| [ p.name, p.id ] }
我需要3个区块,第一个用于子类别的第二类,最后用于选定的子类别。
如果有人帮助我,我将感激不尽。
答案 0 :(得分:0)
表单中的选择标记如下所示:
<%= select_tag "categories", options_for_select(@allcategories, @allcategories.first) %>
<div id="multiselect-subcat">
<%= render :partial => 'subcategories' %>
</div>
添加部分_subcategories.html.erb
<%= form_for @story, :html => {:class => 'form-horizontal'} do |f| %>
<%= f.select(:category_ids, @subcategories.collect { |c| [c.name, c.id] },
{:include_hidden => false},
{:class => 'multi-select', :multiple => true}) %>
<% end %>
添加路线以获取子类别
get 'fetch_subcategories'
def fetch_subcategories
@story = Story.new
@subcategories = Category.where(parent_id: params[:category_id])
render :partial => "subcategories", :locals => { :subcategories => @subcategories }
end
处理类别的更改事件,即更改类别时填充子类别
<script>
jQuery(document).ready(function () {
$('#story_category_ids').multiSelect();
});
jQuery(function($) {
$("#categories").change(function() {
var category = $('select#categories :selected').val();
if(category == "") category="0";
jQuery.get('/stories/fetch_subcategories?category_id=' + category, function(data){
$("#multiselect-subcat").html(data);
$('#story_category_ids').multiSelect();
})
return false;
});
})
</script>