Rails only save record if fields not empty for nes

2019-09-11 07:59发布

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 kidform:

<%= 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!

1条回答
三岁会撩人
2楼-- · 2019-09-11 08:57

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:

def new
    @kid = Kid.new
    5.times do
        @kid.allergies.build
    end
end

to then reject saving any empty relations in the database, in the model you could use something like:

accepts_nested_attributes_for :allergies, reject_if: ->(allergy){ allergy['description'].blank? && allergy['symptoms'].blank? }
查看更多
登录 后发表回答