I am now creating a Rails project and I am using select2
for the form.
form_for in View:
<%= f.fields_for :ingredients do |ingredient_fields|%>
Ingredients: <%= ingredient_fields.select(:name, @ingredients,
{}, multiple: true)%>
<% end %>
javascript file:
$('#cuisine_ingredients_name').select2();
I set @ingredients
in the controller and this is working as it should be, but I don't know how to set the multiple default values for this select2
form.
It seems like initSelection
method is deprecated in version 4.0.0 , and I couldn't find a good example using a new method.
Does anyone have an idea? Thank you in advance.
Okay, after working on this for a while, I figured it out myself.
<%= f.fields_for :ingredients do |ingredient_fields|%>
Ingredients: <%= ingredient_fields.select(:name, @ingredients,
{selected: @selected_ingredients}, multiple: true)%>
Adding a selected option to select
worked for me, as Kevin suggested (Thank you!).
In this example, @selected_ingredients
is defined in edit method in cuisines_controller.
Thank you all for your help!
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.