简体   繁体   中英

Rails multi select defaults

I am working on a script that allows for an admin to assign multiple languages to a user.

I have my multi select working like so:

<%= fields_for :users_languages do |u| %>
        <div class="field">
        <%= @lang_list.inspect %>
            <%= u.label :Assign_Languages %><br />
            <%= select_tag :language_id, options_for_select(Language.all.collect {|lang| [lang.english, lang.id]}),:multiple => true, :prompt => 'Select Language' %>
         </div>
    <% end %>

But when I go in to edit the user their languages are not showing up as auto selected. How would I go about doing this?

Figured it out by doing the following:

Controller:

def edit
    @user = User.find(params[:id])
    @users_langs = UsersLanguage.where("user_id = ?", params[:id])
    @lang_list = []

    @users_langs.each do |langs|
      @lang_list << langs.language_id
    end
  end

I created an array variable called @lang_list, which I then used in my view to tell my multi-select which fields to auto highlight.

View:

<%= fields_for :users_languages do |u| %>
  <div class="field">
      <%= u.label :Assign_Languages %><br />
      <%= select_tag :language_id, options_for_select(Language.all.collect {|lang| [lang.english, lang.id]}, @lang_list),:multiple => true, :prompt => 'Select Language' %>
   </div>
 <% end %>

Hope this helps someone!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM