Deleting records in a has_many through association

I’m working on a project which has a lessons entity and a cards entity. Cards can belong to lessons, or they can exist on their own. In the cases where cards do belong to a lesson, the two entities are connected through a join table called cards_lessons.

I’m in a position where if I delete a lesson which has cards in it, the association in cards_lessons is deleted but the cards themselves still exist. I want the cards to be deleted too.

I think there’s probably something obvious I’m not doing here but can’t spot what it is? Here’s my schema setup:

schema "lessons" do
    has_many(:cards_lessons, CardLesson, on_delete: :delete_all, on_replace: :delete)

    has_many(
      :cards,
      through: [:cards_lessons, :cards],
      on_delete: :delete_all,
      on_replace: :delete
    )
end

schema "cards" do
    has_one(:cards_lessons, CardLesson, on_replace: :delete, on_delete: :delete_all)
    has_one(:lesson, through: [:cards_lessons, :lesson])
end

schema "cards_lessons" do
    belongs_to(:card, Card)
    belongs_to(:lesson, Lesson)
end

Thanks a lot :slight_smile:

I have not done it like this in the schemas but usually do in with database references in the migration file. So in your case, something like

create table(:cards_lessons) do
   add :card_id, references(:cards, on_delete: :delete_all), null: false
  ...
end