希望有人能帮上忙。我有两种型号的订单和日期订单。每个订单可以有多个date_order,我应该能够在创建订单时创建多个date_order。
我该怎么做?正如您所看到的,我的代码可以很好地创建一个日期订单并将其与创建的订单关联起来。
更新:我已经尝试在我的订单/新文件中创建许多"构建器"。它处理了视图,并在我输入多个日期和时间时创建了一个订单。但是fields_for并没有创建任何日期订单。
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 %>
构建更多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
添加到强参数白名单中。