简体   繁体   English

Select2 initSelection已弃用

[英]Select2 initSelection deprecated

I am now creating a Rails project and I am using select2 for the form. 我现在正在创建一个Rails项目,并且正在为表单使用select2

form_for in View: 在视图中使用form_for:

  <%= f.fields_for :ingredients do |ingredient_fields|%>
     Ingredients: <%= ingredient_fields.select(:name, @ingredients,
     {}, multiple: true)%>
   <% end %>

javascript file: javascript文件:

$('#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. 我在控制器中设置了@ingredients ,它应该可以正常工作,但是我不知道如何为该select2表单设置多个默认值。

It seems like initSelection method is deprecated in version 4.0.0 , and I couldn't find a good example using a new method. 似乎initSelection方法在版本4.0.0中已弃用,并且我找不到使用新方法的好的示例。

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!). 正如Kevin所建议的那样,添加一个选定的选项来select对我有用(谢谢!)。

In this example, @selected_ingredients is defined in edit method in cuisines_controller. 在此示例中, @selected_ingredients是在@selected_ingredients中的edit方法中定义的。

Thank you all for your help! 谢谢大家的帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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