0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

子モデルが空なら更新しない belongs_to has_one

Posted at

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_ifattributes.merge!(_destroy: 1)を組み合わせて使う方法もあるそう。
自分の環境では狙い通りに動作しなかった。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?