目前我有两种型号。
class Booking
include Mongoid::Document
include Mongoid::Timestamps
field :capacity, type: Integer
field :date, type:Date
embeds_many :appointments
attr_accessible :capacity, :date, :appointments_attributes
accepts_nested_attributes_for :appointments
end
class Appointment
include Mongoid::Document
field :name, type: String
field :mobile, type: String
embedded_in :booking
end
如何为预约中嵌入的约会创建表单?理想情况下,我希望能够通过指定预订日期将预约添加到预订中。
我可以在控制台中执行此操作,但无法找到为此创建表单的方法。
我试过这个,这不起作用
<%= form_for(@booking) do |f| %>
<div class="field">
<%= f.label :capacity %><br />
<%= f.text_field :capacity %>
</div>
<div class="field">
<%= f.label :date %><br />
<%= f.text_field :date %>
</div>
<h1> form for appointment </h1>
<%= f.fields_for :appointments do |builder| %>
<div class="field">
<%= builder.label :name %><br />
<%= builder.text_field :name %>
</div>
<div class="field">
<%= builder.label :mobile %><br />
<%= builder.text_field :mobile %>
</div>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
预约控制器中的
def create
@booking = Booking.new(params[:booking])
@appointment = @booking.appointments.build(params[:appointments])
respond_to do |format|
if @booking.save
format.html { redirect_to @booking, notice: 'Booking was successfully created.' }
format.json { render json: @booking, status: :created, location: @booking }
else
format.html { render action: "new" }
format.json { render json: @booking.errors, status: :unprocessable_entity }
end
end
end
控制台命令执行表单所要执行的操作:
book = Booking.create(capacity: 10, date: Date.today)
book.appointments.create(name: "Josh", mobile: "19923")
book.appointments.create(name: "Bosh", mobile: "123344")
book.appointments
=> [#<Appointment _id: 51a083c332213f2cc9000002, _type: nil, name: "Josh", mobile: "19923">, #<Appointment _id: 51a0840632213f2cc9000003, _type: nil, name: "Bosh", mobile: "123344">]
答案 0 :(得分:3)
所以我解决了这个问题。我只是使用它自己的控制器和表格来创建应用程序文档,而不是使用嵌套表单。我在应用程序模型中添加了一个日期字段,在控制器内部,我查询了具有该日期的预订文档,并使用该预订创建了应用程序。
这是代码:
def create
date = params[:appointment]['date']
booking = Booking.find_or_create_by(date: date)
@appointment = booking.appointments.new(params[:appointment])
respond_to do |format|
if @appointment.save
format.html { redirect_to booking, notice: 'Appointment was successfully created.' }
format.json { render json: @appointment, status: :created, location: @appointment }
else
format.html { render action: "new" }
format.json { render json: @appointment.errors, status: :unprocessable_entity }
end
end
end