Rails5中删除模型时如何删除模型的所有关联
How to delete all the associations of a model when deleting it in Rails 5
我的项目中有 3 个模型。用户,膳食和食物。
一个用户有很多餐。一顿饭可以有很多食物,一个食物可以是多顿饭的一部分。
用户和膳食模型处于 has_many 关联中,而膳食和食物模型处于 has_many :through 关联中。膳食和食物模型的连接模型称为 MealFood。
删除用户时,我已经这样做了,所以它删除了属于该用户的所有餐点。但是我做不到,所以它也删除了属于用户的所有膳食关联。
我需要删除 meal_foods table 中的每条记录,其中 meal_id 属于要删除的用户。
用户模型
class User < ApplicationRecord
has_many :meals, :dependent => :delete_all
end
膳食模型
class Meal < ApplicationRecord
belongs_to :user, optional: true
has_many :meal_foods, :dependent => :delete_all
has_many :foods, through: :meal_foods
end
食物模型
class Food < ApplicationRecord
has_many :meal_foods
has_many :meals, through: :meal_foods
end
膳食食品模型
class MealFood < ApplicationRecord
belongs_to :meal
belongs_to :food
end
提前致谢!
您可能想要 dependent: :destroy
,而不是 dependent: :delete_all
。 :delete_all
不会 运行 回调,这可能就是为什么你的更深层次的联想仍然存在。
查看文档 here:
For has_many
, destroy
and destroy_all
will always call the destroy
method of the record(s) being removed so that callbacks are run.
However delete
and delete_all
will either do the deletion according to
the strategy specified by the :dependent
option, or if no :dependent
option is given, then it will follow the default strategy. The default
strategy is to do nothing (leave the foreign keys with the parent ids
set), except for has_many :through
, where the default strategy is
delete_all
(delete the join records, without running their callbacks).
This 线程有更好的答案。
我的项目中有 3 个模型。用户,膳食和食物。 一个用户有很多餐。一顿饭可以有很多食物,一个食物可以是多顿饭的一部分。 用户和膳食模型处于 has_many 关联中,而膳食和食物模型处于 has_many :through 关联中。膳食和食物模型的连接模型称为 MealFood。
删除用户时,我已经这样做了,所以它删除了属于该用户的所有餐点。但是我做不到,所以它也删除了属于用户的所有膳食关联。
我需要删除 meal_foods table 中的每条记录,其中 meal_id 属于要删除的用户。
用户模型
class User < ApplicationRecord
has_many :meals, :dependent => :delete_all
end
膳食模型
class Meal < ApplicationRecord
belongs_to :user, optional: true
has_many :meal_foods, :dependent => :delete_all
has_many :foods, through: :meal_foods
end
食物模型
class Food < ApplicationRecord
has_many :meal_foods
has_many :meals, through: :meal_foods
end
膳食食品模型
class MealFood < ApplicationRecord
belongs_to :meal
belongs_to :food
end
提前致谢!
您可能想要 dependent: :destroy
,而不是 dependent: :delete_all
。 :delete_all
不会 运行 回调,这可能就是为什么你的更深层次的联想仍然存在。
查看文档 here:
For
has_many
,destroy
anddestroy_all
will always call the destroy method of the record(s) being removed so that callbacks are run. Howeverdelete
anddelete_all
will either do the deletion according to the strategy specified by the:dependent
option, or if no:dependent
option is given, then it will follow the default strategy. The default strategy is to do nothing (leave the foreign keys with the parent ids set), except forhas_many :through
, where the default strategy isdelete_all
(delete the join records, without running their callbacks).
This 线程有更好的答案。