Rails multi select defaults
I am working on a script that allows for an adm开发者_如何学Goin 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!
精彩评论