Rails - 使用fields_for创建多个嵌套对象

时间:2016-05-01 17:22:22

标签: ruby-on-rails nested-forms form-for fields-for nested-form-for

希望有人可以帮忙解决这个问题。我有两个模型order和date_order。每个订单可以有多个date_orders,我应该能够在创建订单时创建许多date_orders。

我该怎么做?如您所见,我的代码适用于创建一个date_order并将其与创建的订单相关联。

更新:我试图创建许多"构建者"在我的订单/新文件中。它适用于视图,并在我输入多个日期和时间时创建了一个订单。但fields_for没有创建任何date_orders。

orders_controller.rb

def new
    @order = Order.new
    @order.date_orders.build
end

def create
    @order = Order.new(order_params)
    if @order.save
        flash[:success] = "blah"
        redirect_to @order
    else
        render 'new'
    end
end

private

def order_params
    params.require(:order).permit(:user_id, :purpose, 
    date_orders_attributes: [:id, :order_date, :time_start, :time_end, :order_id])
end

order.rb

class Order < ActiveRecord::Base

     has_many :date_orders, :dependent => :destroy
     accepts_nested_attributes_for :date_orders, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true
end

date_order.rb

class DateOrder < ActiveRecord::Base
    belongs_to :order
end

为了/ new.html.erb

<%= form_for(@order, :html => {:multipart => true}) do |f| %>
    ## SOME QUESTIONS ##
    <%= f.fields_for :date_orders do |builder| %>
        <%= builder.label :date %>
        <%= builder.date_field :order_date %>

        <%= builder.label :starting_time %>
        <%= builder.time_field :time_start %>

        <%= builder.label :ending_time %>
        <%= builder.time_field :time_end %>

    <% end %>
<% end %>

1 个答案:

答案 0 :(得分:2)

构建更多orders_dates

class OrdersController < ApplicationController
    def new
        @order = Order.new
        5.times { @order.date_orders.build }   # < === HERE ===
    end

    private

    def order_params
        params.require(:order).permit(:user_id, :purpose, 
        #                                 |-  === HERE ===
        date_orders_attributes: [:id, :content, :order_date, :time_start, :time_end, :order_id])
    end
end

更新

另外,将content添加到您的强参数白名单中。