ruby-on-rails - 在 Rails 5 中删除模型时如何删除模型的所有关联

标签 ruby-on-rails database model-view-controller model associations

我的项目中有 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 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线程有更好的答案。

关于ruby-on-rails - 在 Rails 5 中删除模型时如何删除模型的所有关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49122369/

相关文章:

c# - 将拆分视频保存到数据库中并检索它们

model-view-controller - 基于组件的 MVC 框架和基于 Action 的 MVC 框架

ruby-on-rails - 学习 RoR,有人可以从 H**ll 解释这个 boot.rb 吗?

ruby-on-rails - 搜索#search中的Rails:Elasticsearch::Transport::Transport::Errors::BadRequest

database - 如何使用 SQLQuery 组件运行多个查询?

database - 为什么在 Sqlyog 中将引擎更改为 INNODB 时会生成错误?

iphone - 您如何在 iOS 中将模型与 UIButton(或通常的 UIViews)相关联?

c# - MVC - 域服务负责过滤还是存储库层?

ruby-on-rails - Capybara 问题:@request 必须是 ActionDispatch::Request

ruby-on-rails - 用于 Rails 4 的 mobile_fu