所以,如果我有這個問題,我可能會建立不同的數據庫模型。
而不是一個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
關聯使其成爲免費BlockTime
。
然後,您也可以在此表單中包含所有Appointment
字段。 你可能想煮一些JavaScript來禁用/啓用字段,具體取決於radio_button
選擇
你真的需要它們成爲單獨的模型嗎?看起來像一對夫婦會做的。 –
你可以擴展嗎?當一些記錄沒有記錄時,我將如何處理has_one關聯的情況? – 99miles
只是想大聲。我從來沒有使用STI,所以我可能是錯的。沒關係:) –