[英]Ruby on Rails update model with more than one row in a single form
我有2个模型事件和任务。
活动有很多任务。 任务是事件下的嵌套资源,因此我首先创建一个事件,并询问用户要在其中创建多少个任务。
假设我创建了一个事件,用户想要在其中创建3个任务。 我想分两步去做
成功创建事件后,现在我转到/ events / 1 / tasks / new
这里我想有3个任务名称字段,当用户提交它时,应该针对事件1在任务表中创建3行
我该如何实现
这是任务_form.html.erb
<%= form_for [@event, @task] do |f| %>
<% if @task.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@task.errors.count, "error") %> prohibited this task from being saved:</h2>
<ul>
<% @task.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :content %><br />
<%= f.text_field :content %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
任务控制器
def new
@event=Event.find(params[:event_id])
@event.task_count do
@choice = @event.tasks.build
end
respond_to do |format|
format.html # new.html.erb
format.json { render json: @task }
end
end
# POST /tasks
# POST /tasks.json
def create
@task = Task.new(params[:task])
respond_to do |format|
if @task.save
format.html { redirect_to @task, notice: 'Task was successfully created.' }
format.json { render json: @task, status: :created, location: @task }
else
format.html { render action: "new" }
format.json { render json: @task.errors, status: :unprocessable_entity }
end
end
end
我认为您通过涉及任务控制器使事情变得更加复杂。 控制器在Web应用程序中指挥动作。 但是根据您的描述,您似乎希望在创建事件时自动创建3个任务(如果我对您的理解正确的话)。 除了输入初始名称之外,这实际上并没有涉及用户。
让他们提交名称,当事件控制器创建事件时,应该在此处创建任务。
如果您的嵌套资源更复杂,那么这是嵌套表单的工作。 您可能会受益于此截屏视频:
首先,您以这种方式引入了3个任务
def new
@event=Event.find(params[:event_id])
3.times{@event.tasks.build}
respond_to do |format|
format.html # new.html.erb
format.json { render json: @task }
end
end
然后肯定会针对1个事件创建3个任务。或者您也可以从用于嵌套表单的ryan rails帮助中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.