表格多选 [英] form multiple select
问题描述
我正在学习 Rails,并且已经为此苦苦挣扎了一天多,无法弄清楚如何让它发挥作用.我想要一个可以选择多个元素的表单中的选择框.我用这个代码工作:
<%= f.label :products%><br/><%= f.select :products, {"A"=>1, "B"=>2, "C"=>3, "D"=>4},{},:size=>5,:multiple=>true%>
这可以正常工作并生成此 HTML:
<label for="script_products">产品</label><br/><select id="script_products" multiple="multiple" name="script[products][]" size="5"><option value="1">A</option><option value="2">B</option><option value="3">C</option><option value="4">D</option></select>
我能弄清楚的是如何发送/存储结果.在我看来,显示"操作,如果我只是打印出 :products 我会得到这个:
产品:--- - '1' - '2' - '3'
如果我打印:products.inspect,我会得到这个:
产品:"---\n- '1'\n- '2'\n- '3'\n"
并且类是一个字符串.我认为它会存储为一个数组,但我无法让它工作.我不知道破折号或换行符从何而来.
我会考虑将选项添加为模型上的多个关系.因此,您可以遍历它们,附加它们并以(IMO)更好的方式将它们包含在多重选择中.
我会在我的模型中做类似的事情:
has_many :special_options
在我看来:
f.select :special_options, :multiple =>真的
这将避免在存储对象之前必须序列化和反序列化对象的问题.
I am learning rails and have been struggling with this for over a day now and can not figure out how to get this to work. I want a select box in my form that can select multiple elements. I have this working with this code:
<div class="field">
<%= f.label :products %><br />
<%= f.select :products, {"A"=>1, "B"=>2, "C"=>3, "D"=>4},{},:size=>5,:multiple=>true %>
</div>
This works fine and produces this HTML:
<div class="field">
<label for="script_products">Products</label><br />
<select id="script_products" multiple="multiple" name="script[products][]" size="5">
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option></select>
</div>
What I can figure out is how the results get sent/stored. In my view for the "show" action, if I simply print out :products I get this:
Products: --- - '1' - '2' - '3'
If I print out :products.inspect I get this:
Products: "---\n- '1'\n- '2'\n- '3'\n"
and the class is a string. I would think it would be stored as an array, but I can not get it to work. I don't know where the dashes or the newlines come from.
I would consider adding the options as a has-many relationship on the model. Thus you can iterate through them, attach them and involve them in a multiple select in a (IMO) better way.
I would do something like in my model:
has_many :special_options
In my view:
f.select :special_options, :multiple => true
This would avoid the problem of having to serialize and deserialize the objects before storing them.
这篇关于表格多选的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!