Rails 5:如何处理 simple_form 中的序列化字符串数组?

问题描述

作为标题,我在模型中有一个序列化的字符串列:

class Product < ApplicationRecord
  serialize :ingredient_fields,Array
end

inGrdient_field 有许多字符串,但存储在产品模型中的一列中。它不是嵌套对象。

但我不确定如何使用 simple_form 处理这些动态文本输入,或者我是否可以使用 cocoon 或 nested_form_fields 来处理这些行为。我用这些 gem 尝试了许多不同的方法生成 html,例如:

<form>
  <input name="product[ingredient_fields][]"> <button>remove</button>
  <input name="product[ingredient_fields][]"> <button>remove</button>
  <button>add ingredient</button>
</form>

但都失败了。

还是我只能自己写html和js?

解决方法

您可以在输入名称中插入索引,例如:

<input name="product[ingredient_fields][1]">
<input name="product[ingredient_fields][2]">

所以 rails 将收到一系列产品[ingredient_fields]