我的Ruby on Rails应用程序上有一个非常基本的架构:
公司模式
行业模式(属于某个行业的公司)
子行业模式(子行业属于行业)
在我的活动管理表单页面上,我想放置字段,以便对于每个公司,我首先选择它所属的行业的下拉(到目前为止工作),然后选择另一个字段“子行业”,根据我在前一个领域中选择的行业,我只能展示我之前在这个行业中分类过的子行业。
例如,古柯将进入行业“饮料和饮料”,我希望动态调整表格,只在“sub indsutry”字段中显示:“热饮”,“冷饮”下拉, “茶”,“苏打水”
form do |f|
f.inputs "Company" do
f.input :company_industry_id, :label => "Select industry:", :as => :select, :collection => CompanyIndustry.all
f.input :company_subindfustry_id, :label => "Select subindustry:", :as => :select, :collection => CompanySubindustry.all
end
显然我到目前为止遇到了一个问题,它向我展示了我所拥有的所有子行业,而不仅仅是我在前一个领域选择的行业中的子行业。
有谁知道如何解决这个问题?
答案 0 :(得分:5)
我选择以快速而肮脏的非AJAX方式处理这个问题。它适用于我的场景。
请注意,辅助选择中的不适用项目已禁用,而不是隐藏。如果你真的需要隐藏它们,我会克隆&重建select而不是禁用特定选项。
#...
f.input :user, :input_html => {
##Manipulate Location select based on selected User
:onchange => "
var user = $(this).val();
$('#order_location_id').val(0).find('option').each(function(){
var $option = $(this),
isCorrectUser = ($option.attr('data-user') === user);
$option.prop('disabled',!isCorrectUser);
});
"
}
##Insert necessary Location info into DOM
f.input :location, collection: Location.all.map{ |loc|
[loc.name,loc.id, {"data-user" => loc.user_id}]
}
#...
答案 1 :(得分:2)
您需要执行页面刷新以根据所选内容更新数据,或者(我的偏好)进行AJAX调用以在选择第一个下拉列表后更新其他下拉列表。
这样做有一个很棒的railscast - 这将是一个很好的起点。