问题描述
在我的Rails应用程序中,我有一个 Kid
模型和一个 Allergy
模型,其中 Kid
具有很多过敏
.我还创建了一个嵌套表单,以便在创建新的 kid
时, allergy
字段处于 kid
表单中.这是我的 kid
控制器中的内容:
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
这是在我的index.html.erb中,该嵌套在我的create kid
表单中:
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%>
这仅适用于在 Allergy
模型中插入一个 Allergy
记录,但是我希望能够列出最多5个 Allergy
输入,并且仅插入用户填写的内容,因为儿童
可能会有可变数量的过敏
.
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
.
我使用了这篇文章: 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:
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? }
这篇关于Rails仅在字段嵌套形式的字段不为空的情况下保存记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!