我有一个像这样的大型哈希,它有车辆的品牌和型号:
makes_models = {" AM General":[" Hummer"]," Acura":[" CL"," ILX"," ILX Hybrid"," Integra"," Legend"," MDX"," NSX"," RDX", " RL"," RLX"," RSX", " SLX"," TL"," TLX"," TSX"," TSX Sport Wagon"," ; Vigor"," ZDX"]," Alfa 罗密欧":[" 4C"],"阿斯顿马丁":[" DB7"," DB9"," DBS& #34;," Rapide"," Rapide S"," V12 Vanquish"," V12 Vantage"," V8 Vantage"," Vanquish", " Virage"],"奥迪":[" 100"," 200"," 80",&#34 ; 90"," A3"," A3 e-tron"," A4", " A5"," A6"," A7"," A8"," Cabriolet"," Coupe& #34;," Q1"," Q3"," Q5"," Q7", " R8"," RS 4"," RS 5"," RS 6"," RS 7",& #34; S3"," S4"," S5"," S6"," S7", " S8"," SQ5"," TT"," TT RS"," TTS"," V8"," allroad"," allroad QUATTRO"]}
我有一个select,可以让你选择模型的哈希键:
<%= vehicle.select(:make, options_for_select(["AM General", "Acura", ...] )) %>
我有jQuery根据所选的make更新模型选择:
$('select#quote_vehicles_make').change(function() {
$.each(models[$(this).val()], function( idx, value ) {
$('select#quote_vehicles_models').html("<option>" + value + "</option>");
});
});
模特选择:
<select id="quote_vehicles_models">
<option>...</option>
</select>
问题是select只返回makes_models
哈希中的最后一个值。因此,例如,如果我选择: Acura ,则模型会选择更新并仅显示: ZDX
答案 0 :(得分:0)
我解决了自己的问题:jQuery:
$('select#quote_vehicles_make').change(function() {
$('select#quote_vehicles_models').empty();
$.each(models[$(this).val()], function( idx, value ) {
$('select#quote_vehicles_models').append("<option>" + value + "</option>");
});
});
如果存在Rails导向解决方案仍然感兴趣。感谢。
答案 1 :(得分:0)
在这里考虑数据结构:
def make
{"AM General":["Hummer"], "Acura":["CL", "ILX", "ILX Hybrid", "Integra", "Legend", "MDX",
"NSX", "RDX", "RL", "RLX", "RSX", "SLX", "TL", "TLX", "TSX", "TSX Sport Wagon", "Vigor", "
ZDX"], "Alfa Romeo":["4C"], "Aston Martin":["DB7", "DB9", "DBS", "Rapide", "Rapide S", "V12
Vanquish", "V12 Vantage", "V8 Vantage", "Vanquish", "Virage"], "Audi":["100", "200", "80",
"90", "A3", "A3 e-tron", "A4", "A5", "A6", "A7", "A8", "Cabriolet", "Coupe", "Q1", "Q3",
"Q5", "Q7", "R8", "RS 4", "RS 5", "RS 6", "RS 7", "S3", "S4", "S5", "S6", "S7", "S8", "SQ5",
"TT", "TT RS", "TTS", "V8", "allroad", "allroad quattro"]}[model]
end
然后你可以为每辆车制作一个模型列表,如:
make[@vehicle.model]
您也可以使用jquery执行此操作,只需将make函数定义为javascript函数,获取所选模型,并将其传递给make函数。输出将是该模型的一个品牌数组,然后您可以将其作为下一个选择框的html选项传入。