I have 3 models in my project. User, Meal & Food. A user has many meals. A meal can have many food items and a food item can be a part of many meals. The user and the meal model are in a has_many association, while the meal and the food model are in a has_many :through association. The join model for the meal and the food model is called MealFood.
When deleting the user I have made it so that it deletes all of the meals that belong to the user. However I can't make it so that it also deletes all the associations of the meal that belong to the user.
I need to delete every record in the meal_foods table where the meal_id belongs to the user that is being deleted.
User Model
class User < ApplicationRecord
has_many :meals, :dependent => :delete_all
end
Meal Model
class Meal < ApplicationRecord
belongs_to :user, optional: true
has_many :meal_foods, :dependent => :delete_all
has_many :foods, through: :meal_foods
end
Food Model
class Food < ApplicationRecord
has_many :meal_foods
has_many :meals, through: :meal_foods
end
MealFood Model
class MealFood < ApplicationRecord
belongs_to :meal
belongs_to :food
end
Thanks in advance!
You probably want dependent: :destroy, not dependent: :delete_all. :delete_all won't run callbacks and that's likely why your deeper associations remain persisted.
See the docs here:
For
has_many,destroyanddestroy_allwill always call the destroy method of the record(s) being removed so that callbacks are run. Howeverdeleteanddelete_allwill either do the deletion according to the strategy specified by the:dependentoption, or if no:dependentoption 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 thread has better answers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With