views:

37

answers:

2

UPDATE

@selected
attributes: 
group_id: "29"
attributes_cache: {}
@data
attributes: 
created_at: 2010-06-19 10:16:13
term_id: "1"
updated_at: 2010-06-19 10:16:13
id: "29"
course_id: "1"

Hi,

I am trying to pre-select items within a select_tag

 <%= select_tag "contact[group_ids][]",
       options_for_select(
         @data.map{ |d| [" Term #{d.term.number} #{d.term.start_date} #{d.course.course_type} #{d.course.course_name}"] },
         @selected.map{ |j| j.id }
       ),
       :multiple => true
%>

The @data object is all the items in the list and @selected contains the id's of the ones that should be selected.

Any ideas why they are not being selected ?

Thanks, Alex

A: 

I believe it's just

<%= select_tag "contact[group_ids][]",
       options_for_select(
         @data.map{ |d| [" Term #{d.term.number} #{d.term.start_date} #{d.course.course_type} #{d.course.course_name}"] },
         @selected
       ),
       :multiple => true
%>

because railsapi.com says:

"selected may also be an array of values to be selected when using a multiple select"

Edit

I thought @selected was an array of IDs, but it isn't. So the way you first write your code (with @selected.map{ |j| j.id }) should work.

j.
thanks for the reply, I tried that after looking at the api but had no luck. I have added what my objects look like, are they ok ?
Alex
I thought `@selected` was an array of IDs... But `@selected.map{ |j| j.id }` should work then :/
j.
A: 

You can do this by using - options_from_collection_for_select()

http://shiningthrough.co.uk/Select-helper-methods-in-Ruby-on-Rails

Alex