Rails select tag with multiple preselected values

I am trying to have multiple blocks of choice. select will contain all the stores in the database, but those that belong to the user will be selected.

I'm halfway there. I have a selection box that has all the stores in the database. I cannot select those to which the user belongs.

I have the following:

<%= select_tag 'stores[]', options_for_select(@stores.map {|s| [s.store_name, s.store_id]}, :selected => @user.stores.map {|j| [j.store_name, j.store_id]}), :multiple => true, :size => 10 %> 

I have a map with stores to which the user belongs. he is in:

 @user.stores 
+31
ruby-on-rails
Feb 03 '10 at 23:48
source share
2 answers

after enough trial and error, the following worked for me:

 <%=select_tag 'stores[]', options_for_select( @stores.map {|s| [s.store_name, s.store_id]}, @user.stores.pluck(:id) ), :multiple => true, :size => 10%> 
+48
Feb 04 '10 at 0:21
source share

Another way to do this is to use the options_from_collection_for_select helper method. It will look something like this:

 <%= select_tag 'stores[]', options_from_collection_for_select(@stores, :store_id, :store_name, [4,5,6]), multiple: true, size: '10%' %> 
+11
Apr 30 '13 at 21:04
source share



All Articles