したがって、この問題が発生した場合は、おそらくデータベースを別の方法でモデル化するでしょう。
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
フィールドを含めることができます。選択に応じてフィールドを無効/有効にするために、いくつかのJavaScriptを作成することをお勧めしますradio_button