ImranNaqvi ImranNaqvi - 3 months ago 27
Ruby Question

Repopulate Multiple select Box - Ruby On Rails

I am using

html.erb
templates and
bootstrap
.when creating a post i choose multiple options from select box and save these values in database in the form of array because i'm using
serialize :column_name
option in my model . it works so far . but when i try to edit the post , select box values donot repopulate . I have tried the below options

My select box in _form.html.erb

<%= form_for(@post , url: { action: @definded_action }) do |f| %>
<%= f.select :skills, options_from_collection_for_select(@skills , :id,:title), {}, id: "sel1" ,class: "form-control selectpicker" , multiple: true%>
<% end %>


when i debug in edit function where i am fetching skills , it shows me

@post.skills = ["1","2","3","4"]


in edit function where i'm fetching it from database i have tried this

@post.skills = @post.skills.map(:&to_i)


but no success. any help will be greatly appreciated :) -

Answer

Can you try the following, its same as you except its collection_select:

<%= f.collection_select :skills, @skills, :id, :title, {selected: @post.skills.map(:&to_i)}, { multiple: true, id: "sel1", class: "form-control selectpicker", placeholder: "Select Skill."} %>
Comments