Ruby on rails 在Rails 5中删除模型时如何删除模型的所有关联
我的项目中有3个模型。用户、膳食和食品。 一个用户有很多餐。一顿饭可以有很多种食物,一种食物可以是很多顿饭的一部分。 用户和膳食模型处于has\u many关联中,而膳食和食品模型处于has\u many:through关联中。膳食和食物模型的联接模型称为MealFood 当删除用户时,我已将其设置为删除所有属于该用户的膳食。但是,我无法使它同时删除属于用户的所有膳食关联 我需要删除Dine_foods表中的每条记录,其中Dine_id属于要删除的用户 用户模型Ruby on rails 在Rails 5中删除模型时如何删除模型的所有关联,ruby-on-rails,database,model-view-controller,model,associations,Ruby On Rails,Database,Model View Controller,Model,Associations,我的项目中有3个模型。用户、膳食和食品。 一个用户有很多餐。一顿饭可以有很多种食物,一种食物可以是很多顿饭的一部分。 用户和膳食模型处于has\u many关联中,而膳食和食品模型处于has\u many:through关联中。膳食和食物模型的联接模型称为MealFood 当删除用户时,我已将其设置为删除所有属于该用户的膳食。但是,我无法使它同时删除属于用户的所有膳食关联 我需要删除Dine_foods表中的每条记录,其中Dine_id属于要删除的用户 用户模型 class User <
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
class用户:全部删除
结束
膳食模式
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
课堂用餐:全部删除
有很多:食物,通过:餐食
结束
食品模型
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
食品类
MealFood模型
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
class MealFood
提前谢谢 您可能想要
dependent::destroy
,而不是dependent::delete\u all
<代码>:delete_all不会运行回调,这可能就是您的深层关联保持不变的原因
见文件:
因为有许多
,销毁
和销毁_所有
将始终调用销毁
删除记录以便运行回调的方法。
但是delete
和delete\u all
将根据
由:dependent
选项指定的策略,或者如果没有:dependent
选项,则它将遵循默认策略。默认值
策略是什么都不做(将外键保留在父ID中)
设置),除了默认策略为
delete_all
(删除加入记录,而不运行其回调)
线程有更好的答案。你的意思是
dependent::destroy
,而不是dependent:destroy\u all
,因为我得到了这个错误语法错误,意外的“:”,期望关键字\u end有很多:饭,:dependent:destroy\u all
谢谢你,它成功了!因为我使用的是Deviate,所以在删除它时遇到了一个问题,但事实证明,这是因为我使用的连接模型没有id列。只是说,如果有人有相同的问题,只需添加一个主键到您的联接表!