开发者

Rails, collection_select - remembering values with :selected after form submitted

开发者 https://www.devze.com 2023-01-31 06:51 出处:网络
(Using Rails 2.3.5 on an internal work server with no choice of versions, and I\'m pretty new) I\'m building a search form where I need to provide a list of directories to a user so they can select w

(Using Rails 2.3.5 on an internal work server with no choice of versions, and I'm pretty new)

I'm building a search form where I need to provide a list of directories to a user so they can select which one(s) to search against. I'm trying to figure out how to get the selected values of a collection_select to remain after the form is submitted.

Say the user selected 3 directories from the collection_select, the id's of those directories would look like this in the params:

directory: !map:HashWithIndifferentAccess 
  id: 
  - "2"
  - "4"
  - "6"

I know that you can manually specify multiple selected items:

<%= collection_select :directory, :id, @directories, :id, :name,
                 {:selected => [2,4,6]}, {:size => 5, :multiple => true} %>

I've also played around a bit and was able to us "to_i" against a single value in the params hash:

<%= collection_select :directory, :id, @directories, :id, :name,
                 {:selected => params[:directory][:id][0].to_i}, {:size => 5, :multiple => true} 开发者_如何学Go%>

What I can't figure out is how to use all of the values of the :directory params at the same time so what the user selected remains after the form is submitted. Thanks for any help.


I'm not precisely sure what you're asking, but if you're trying to get the array of strings in params[:directory][:id] as an array of integers, all you need is

params[:directory][:id].map{|id|id.to_i}
0

精彩评论

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