使用 fields_for 创建多条记录 - Rails [英] Create Multiple records with fields_for - Rails
问题描述
我有两个模型,task
和 list_items
.一个 task
有_many list_items
.但是我希望能够创建 task
和许多 list_items
如果用户想要所有这些都在一种形式中.这是目前的样子:
I have two models, task
and list_items
. a task
has_many list_items
. But I want to be able to be able to create task
and many list_items
if the user wants all in one form. Here is what it looks like currently:
<%= form_for @task, url: account_assignment_tasks_path(@assignment), method: :create do |form| %>
<%= form.text_field :description, class: "form-input #{error_class}" %>
<%= fields_for :list_items, @all_list_items do |list_item_form| %>
<%= list_item_form.text_field :description, class: "form-input list-item", data: { list_item_field: "true" } %>
<% end %>
<% end %>
任务控制器
def new
@task = @assignment.tasks.new
@list_item = @task.list_items.build
@all_list_items = []
end
基本上我要做的是创建多个列表项和一项创建任务.但是现在如果我提交表单,我会收到这个错误
Basically what I'm trying to do is create multiple list items and one task on create. But right now I'm getting this error if I submit the form
undefined method `description' for []:Array
有人知道我做错了什么以及我如何做到这一点吗?
Does anybody know what I'm doing wrong and how I can achieve this?
推荐答案
[]:Array 的未定义方法 `description'
undefined method `description' for []:Array
为了描述错误的原因,fields_for
接受 record_object
作为第二个参数,fields_for
用它来构造强>领域.这里传递的是 @all_list_items
,它是一个数组,会导致错误.
To describe the reason for the error, fields_for
accepts record_object
as a second parameter which fields_for
uses it to construct the fields. Here you are passing @all_list_items
which is an array and that results in the error.
错误的解决方法:
你应该通过 @list_item
而不是 @all_list_items
You should pass @list_item
instead of @all_list_items
<%= fields_for :list_items, @list_item do |list_item_form| %>
实际问题的解决方案:
因为你想创建多个list_items
,你应该这样做
As you want to create multiple list_items
, you should do
def new
@task = @assignment.tasks.new
x.times do
@list_item = @task.list_items.build
end
@all_list_items = []
end
其中x
是你要创建多少个list_items
,比如你要创建三个list_items
,那么替换x
和 3
.
where x
is how many list_items
you want to create, for example if you want to create three list_items
, then replace x
with 3
.
或
使用 cocoon gem 动态创建嵌套表单.
Use cocoon gem to dynamically create nested forms.
这篇关于使用 fields_for 创建多条记录 - Rails的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!