简体   繁体   English

Rails从单个表单创建多个行

[英]Rails creating more than one row from a single form

I don't know if I am doing this in a wrong way but here is it. 我不知道我是否以错误的方式进行操作,但这就是它。

I have 2 models Event and Tasks. 我有2个模型事件和任务。

Event has many tasks. 活动有很多任务。 and task is a nested resource under event so I first create a event and ask a user how many tasks it wants to create in it. 任务是事件下的嵌套资源,因此我首先创建一个事件,并询问用户要在其中创建多少个任务。

Let say I create a Event and a user wants to create 3 tasks in it. 假设我创建了一个事件,用户想要在其中创建3个任务。 I want to do it in 2 steps and not one 我想分两步去做

After successful creation of event,now I go to /events/1/tasks/new 成功创建事件后,现在我转到/ events / 1 / tasks / new

here I want to have 3 task name fields and when the user submits it, there should be 3 rows created in Task table against the Event 1 这里我想有3个任务名称字段,当用户提交它时,应该针对事件1在任务表中创建3行

How do I achieve this 我该如何实现

So here is the task _form.html.erb 这是任务_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 %>

Task controller 任务控制器

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

You can try like this 你可以这样尝试

 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM