If I save an array to the database, it is persisted properly, but when I look at the form, it puts concatenated values in the array in all array input fields.
E.g. in the form below I have 2 input fields, so you can store 2 nicknames for a Pet inside the array column. I put "a" in field 1 and "b" in field 2 and press save. I inspect in the Rails console and it's stored correctly: nicknames: ["a", "b"]. But when I open up the form, both input fields contain "a b". So the values are concatenated somehow. What am I doing wrong?
To reproduce:
rails g scaffold Pets
Then in the new migration:
class CreatePets < ActiveRecord::Migration
def change
create_table :pets do |t|
t.string :nicknames, array: true
t.timestamps null: false
end
end
end
In the controller:
def pet_params
params[:pet].permit(nicknames: [])
end
In the form:
<%= simple_form_for(@pet) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.text_field :nicknames, name: 'pet[nicknames][]' %>
<%= f.text_field :nicknames, name: 'pet[nicknames][]' %>
</div>
<div class="form-actions">
<%= f.button :submit %>
</div>
<% end %>
Create a new Pet with nicknames "a" and "b". Go to edit the Pet and the inputs now contain "a b" and "a b", but it's stored as 'nicknames: ["a", "b"]' in the database according to the Rails console.
Nicknameand set up a relationship so that Pets will have many nickname and nickname belongs to Pet, then using nested form. If you still want to do in this way, maybe this article can help you: tenforward.consulting/blog/…@petsis persisted, than iterate@pets.nicknamesand insert separate text field with value of nickname.