parent 类型更改时删除 children

Delete children when parent type changes

我有这个代码:

class FlexField < ActiveRecord::Base
  has_many :flex_field_values, class_name: 'FlexFieldValue'
  after_save :delete_flex_values

  def delete_flex_values
    if self.field_type != 'list'
      self.flex_field_values.delete_all
    end
  end

目标是在类型不是列表的情况下删除所有值。现在发生的事情是,一旦我将类型设置为列表以外的其他内容,children 的 none 就会被删除,但它们的 flex_field_id 会被设置为空。

我怎样才能真正删除它们?

你可以这样写:

class FlexField < ActiveRecord::Base
  has_many :flex_field_values, class_name: 'FlexFieldValue', dependent: :destroy
  after_save :delete_flex_values

  def delete_flex_values
    if self.field_type != 'list'
      self.flex_field_values.clear
    end
  end
end

关于collection.clear的简要想法:

Removes every object from the collection. This destroys the associated objects if they are associated with dependent: :destroy, deletes them directly from the database if dependent: :delete_all, otherwise sets their foreign keys to NULL. If the :through option is true no destroy callbacks are invoked on the join models. Join models are directly deleted.