所以,如果我遇到这个问题,我可能会对数据库进行不同的建模。
我会使用组合模式,而不是STI/继承模式。所以:
class Appointment
belongs_to :block_time, :class_name => "BlockTime"
...
end
class BlockTime
has_one :appointment
accepts_nested_attributes_for :appointment, :allow_destroy => :true,
:reject_if => :all_blank
...
end
控制器
class AppointmentsController < ApplicationController
...
def new
@block_time = BlockTime.new
@block_time.appointment or @block_time.build_appointment
...
end
def edit
@block_time = BlockTime.includes(:appointment).find(params[:id])
@block_time.appointment or @block_time.build_appointment
end
...
end
表格或表格的至少一部分
<%= f.fields_for :appointment do |g| %>
<div>
<%= g.radio_button :_destroy, "1", :checked => !g.object.persisted? %>
<%= g.label :_destroy_1, "Has no Appointment" %>
<%= g.radio_button :_destroy, "0", :checked => g.object.persisted? %>
<%= g.label :_destroy_0, "Has Appointment" %>
</div>
<p>
Client: <%= g.text_field :client %>
</p>
<% end %>
这部分表单用于persisted?
检查Appointment
对象是新记录还是已持久化到数据库中。然后,如果它已经存在并且您想将其删除,那么它将抛出_destroy
标志accepts_nested_attributes_for
并删除现有appointment
关联以使其成为 free BlockTime
。
然后您也可以Appointment
在此表单中包含所有字段。您可能想根据radio_button
选择编写一些 javascript 来禁用/启用字段