Michael Horojanski
Michael Horojanski

Reputation: 4701

Cascade of deletes ActiveRecord

How can add a cascade of deletes that will remove Profile, TodoList, and TodoItem rows for any User removed.

User Model:

class User < ActiveRecord::Base
  has_one :profile
  has_many :todo_lists
  has_many :todo_items, through: :todo_lists, source: :todo_items
  validates :username, presence: true
  end

Profile Model:

class Profile < ActiveRecord::Base
     belongs_to :user

     validates :first_name, presence: true
     validates :last_name, presence: true

     validates :gender, inclusion: %w(male female)

     validate :first_and_last
     validate :male_Sue


    def first_and_last
      if (first_name.nil? and last_name.nil?)
        errors.add(:base, "Specify a first or a last.")
      end
    end

    def male_Sue
      if (first_name == "Sue" and gender == "male")
        errors.add(:base, "we are prevent male by name Sue.")
      end
    end
  end

TodoList Model:

class TodoList < ActiveRecord::Base

    belongs_to :user
    has_many :todo_items, dependent: :destroy
    default_scope { order :list_due_date }
  end

TodoItem Model:

class TodoItem < ActiveRecord::Base
  belongs_to :todo_list

  default_scope {order :due_date }
end

Thanks, Michael.

Upvotes: 0

Views: 218

Answers (2)

x6iae
x6iae

Reputation: 4164

From the docs:

has_many, has_one and belongs_to associations support the :dependent option. This allows you to specify that associated records should be deleted when the owner is deleted

By using dependent: :destroy on your association in the User class, anytime you destroy a User, all associated objects to that instance gets destroyed as well.

You can check this documentation for more information.

Upvotes: 1

Pavan
Pavan

Reputation: 33542

I guess adding dependent: :destroy will do.

#user.rb
class User < ActiveRecord::Base
  has_one :profile, dependent: :destroy
  has_many :todo_lists, dependent: :destroy
  has_many :todo_items, through: :todo_lists, source: :todo_items, dependent: :destroy
  validates :username, presence: true
end

Upvotes: 1

Related Questions