Rails从单个表单创建多个行

时间:2012-03-28 06:47:26

标签: ruby-on-rails forms

我不知道我是否以错误的方式这样做但是就是这样。

我有2个模型事件和任务。

活动有很多任务。和task是事件下的嵌套资源 所以我首先创建一个事件并询问用户要在其中创建多少个任务。

假设我创建了一个事件,用户想在其中创建3个任务。我想分两步而不是一步

成功创建活动后,现在转到/ events / 1 / tasks / new

这里我希望有3个任务名称字段,当用户提交时,应该在Task表中针对事件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

1 个答案:

答案 0 :(得分:0)

您可以尝试这样

 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