开发者

form multiple select

开发者 https://www.devze.com 2023-04-03 19:56 出处:网络
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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消