Rails 3.验证失败时,保持表单中嵌套字段的数量

时间:2022-12-09 10:19:51

I have a form where I register a Student and 3 Emergency Contacts. (emergency_contact belongs to student).

我有一个表格,我注册了学生和3个紧急联系人。 (emergency_contact属于学生)。

So, StudentsController...

那么,StudentsController ......

def new
  @student = Student.new
   3.times {@student.emergency_contacts.build}
...

So let's say, the user filled out student information and only ONE emergency contact. The validation fails for any reason (maybe student name wasn't entered), when the form is redisplayed, the fields to enter a second or third additional emergency contacts are gone.

因此,假设用户填写了学生信息,只填写了一个紧急联系人。验证因任何原因(可能未输入学生姓名)而失败,当表格重新显示时,输入第二个或第三个其他紧急联系人的字段消失。

Of course, if I do this 3.times {@member.caregivers.build} in the create action too, I will get more and more additional fields each time the validation fails.

当然,如果我也在创建操作中执行3次{@ member.caregivers.build},那么每次验证失败时我都会获得越来越多的附加字段。

So how can I always keep a specified number of nested models in a form, even after the validation fails?

那么,即使在验证失败后,如何始终在表单中保留指定数量的嵌套模型?

1 个解决方案

#1


1  

In your create action, you can do:

在您的创建操作中,您可以:

if @student.save
  ...
else
 (3 - @student.emergency_contacts.size).times { @student.emergency_contacts.build }
end

hope it helps.

希望能帮助到你。

#1


1  

In your create action, you can do:

在您的创建操作中,您可以:

if @student.save
  ...
else
 (3 - @student.emergency_contacts.size).times { @student.emergency_contacts.build }
end

hope it helps.

希望能帮助到你。