Add a class to each select options with SimpleForm

送分小仙女□ 提交于 2019-12-22 09:57:47

问题


I want to build a select input from an array (and not a collection of models), with SimpleForm, and have different classes for each options.

I would have hoped that this would work:

f.input :method, collection: [
    ["option text", "option_value_1", { class: "class_name_1" }],
    ["option text 2", "option_value_2", { class: "class_name_2" }]
]

The problem with that is it will generate:

<select>
    <option value="option text" class="class_name_1">option text</option>
    <option value="option text 2" class="class_name_2">option text 2</option>
</select>

How can I do what I want (value should be "option value") with simple form?


回答1:


This appears to be a limitation when using collections, see the author of SimpleForm's explanation here. He recommends a workaround of the form:

f.input :method, :as => :select do
  f.select :method, [['option text', 'option_value_1', {"class" => "class_name_1"}], ['option text 2', 'option_value_2', {"class" => "class_name_2"}]]
end



回答2:


You also can pass array of arrays as an argument

= f.input :status, collection: [['option text', 'option_value_1', {"class" => "class_name_1"}], ['option text 2', 'option_value_2', {"class" => "class_name_2"}]]


来源:https://stackoverflow.com/questions/15190988/add-a-class-to-each-select-options-with-simpleform

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!