mark_for_destruction
のフラグを立てる
DBにデータがあればchild
が削除され、なければそのままparent
だけ登録される。
子モデルにrequired: false
を設定しないと、子モデルの値が空のときに[xxx を入力してください]的なバリデーションエラーになる。
child.rb
class Child < ApplicationRecord
belongs_to :parent, required: false
end
parent.rb
class Clip < ApplicationRecord
has_one :, :child => :destroy
accepts_nested_attributes_for :child
before_save :set_destroy
def set_destroy
self.child.mark_for_destruction if self.child.present? && self.child.name.blank?
end
別の方法
nested attributes なレコードを、特定の属性が空の時に削除する
reject_if
とattributes.merge!(_destroy: 1)
を組み合わせて使う方法もあるそう。
自分の環境では狙い通りに動作しなかった。