In my Rails application I have a Kid
model and an Allergy
model where a Kid
has_many Allergies
. I have also created a nested form so that the allergy
fields are in the kid
form when creating a new kid
. This is what I have in my kid
controller:
def new
@kid = Kid.new
allergy = @kid.allergies.build
end
and this is in my index.html.erb nested in my create kid
form:
<%= f.fields_for :allergies, Allergy.new do |u| %>
<%= u.label :description, "Description", class: "control-label" %>
<%= u.text_field :description, class: "input-sm form-control" %>
<%= u.label :symptoms, "Symptoms", class: "control-label", %>
<%= u.text_field :symptoms, class: "input-sm form-control" %>
<%end%>
This works fine for inserting just one allergy
record into the Allergy
model, however I want to be able to list up to 5 allergy
inputs, and only insert those ones that a user fills, as a kid
could have a variable amount of allergies
.
I used this article: http://vicfriedman.github.io/blog/2015/07/18/create-multiple-objects-from-single-form-in-rails/
However, I could not make this work for a nested form. All help is appreciated, thanks!
to get multiple nested forms for your relations you will need to build the number of related items you want to display in the form, something like:
to then reject saving any empty relations in the database, in the model you could use something like: