Rails 5: How to handle serialized string array in simple_form?

264 Views Asked by At

As title, I have a serialized string column in the model:

class Product < ApplicationRecord
  serialize :ingredient_fields, Array
end

The ingrdient_field has many strings, but store in one column within the product model. It is not nested objects.

But I'm not sure how to handle these dynamic text inputs use simple_form, or if I can use cocoon or nested_form_fields to handle the behaviors. I tried many different ways with these gems to generate the html like:

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

but all failed.

Or I can only write html and js myself?

1

There are 1 best solutions below

0
Chuyi Huang On

you can insert index into input names, for example:

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

so rails will receive an array of products[ingredient_fields]