2013-01-21 143 views

回答

1

好吧,我會用categorysubcategory模型寫一個例子。

首先是車型之間的關係:與simple_form gem(你可以用form_for做)

class Category 
has_many :subcategories 
has_many :objects 
end 

class Subcategory 
belongs_to :category 
has_many :objects 
end 

class Object 
belongs_to :category 
belongs_to :subcategory 
end 

現在上查看的格式,例如:

<%= simple_form_for(@object, :html => {:multipart => true }) do |f| %> 
<%= f.input :category, :collection => Category.all :prompt => "Select Category" %> 
<%= f.input :subcategory, :label_html => { :class => 'subcategory_label_class' } do %> 
<%= f.grouped_collection_select :subcategory_id, Category.order_by(:title), :subcategories, :title, :id, :name, include_blank: true %> 
<% end %> 
<%= f.button :submit %> 
<% end %> 

有了這個,我們分組的子類別與他們的父類別。

下一步必須將代碼添加到您的objects.js.coffee

$('#object_subcategory_id').parent().hide() 
    subcategories = $('#object_subcategory_id').html() 
    $('#object_category').change -> 
    category = $('#object_category :selected').text() 
    escaped_category = category.replace(/([ #;&,.+*~\':"!^$[\]()=>|\/@])/g, '\\$1') 
    options = $(subcategories).filter("optgroup[label='#{escaped_category}']").html() 
    if options 
     $('#object_subcategory_id').html(options) 
     $('.subcategory_label_class').show() 
     $('#object_subcategory_id').parent().show() 
    else 
     $('#object_subcategory_id').empty() 
     $('.subcategory_label_class').hide() 
     $('#object_subcategory_id').parent().hide() 

可以適應這個例子您的需求。

我希望它有幫助。

問候!