删除所有者时从记录中删除引用 ID
Remove the reference id from the record when the owner is deleted
假设我有一个 Post
模型:
class Post < ActiveRecord::Base
belongs_to :category
end
和一个Category
模特:
class Category < ActiveRecord::Base
has_many: :posts
end
我可以使用 dependent: :destroy
在删除特定类别时删除所有帖子,但我不想删除帖子,我只想删除与该特定类别的关联将这些帖子的 category_id
列设置为 nil
。
是否有 "Rails Way" 开箱即用的方法,或者我是否需要使用一些回调?
使用依赖::nullify
根据 Rails 指南:
:nullify causes the foreign key to be set to NULL. Callbacks are not
executed.
所以你有:
class Category < ActiveRecord::Base
has_many: :posts,
dependent: :nullify
end
假设我有一个 Post
模型:
class Post < ActiveRecord::Base
belongs_to :category
end
和一个Category
模特:
class Category < ActiveRecord::Base
has_many: :posts
end
我可以使用 dependent: :destroy
在删除特定类别时删除所有帖子,但我不想删除帖子,我只想删除与该特定类别的关联将这些帖子的 category_id
列设置为 nil
。
是否有 "Rails Way" 开箱即用的方法,或者我是否需要使用一些回调?
使用依赖::nullify
根据 Rails 指南:
:nullify causes the foreign key to be set to NULL. Callbacks are not executed.
所以你有:
class Category < ActiveRecord::Base
has_many: :posts,
dependent: :nullify
end