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!