我的项目中有 3 个模型。用户,膳食和食物。 一个用户有很多餐。一顿饭可以有很多食物,一个食物可以是多顿饭的一部分。 用户和膳食模型处于 has_many 关联中,而膳食和食物模型处于 has_many :through 关联中。膳食和食物模型的连接模型称为 MealFood。
删除用户时,我已经这样做了,因此它删除了属于该用户的所有餐点。但是我做不到,所以它也删除了属于用户的所有膳食关联。
我需要删除 meal_foods 表中的每条记录,其中 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
MealFood 模型
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线程有更好的答案。
关于ruby-on-rails - 在 Rails 5 中删除模型时如何删除模型的所有关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49122369/