Delete & destroy association

  1. delete 沒有 dependent: :destroy只清空*_id

  2. delete 有 dependent: :destroy皆刪除record

  3. destroy 不論有無dependent: :destroy皆刪除record

delete

class Person < ActiveRecord::Base
  has_many :pets
end


person.pets.delete(Pet.find(1))
Pet.find(1)
# => #<Pet id: 1, name: "Fancy-Fancy", person_id: nil>


class Person < ActiveRecord::Base
  has_many :pets, dependent: :destroy
end

person.pets.delete(Pet.find(1))
Pet.find(1)
# => ActiveRecord::RecordNotFound: Couldn't find all Pets with 'id': (1)

destroy

class Person < ActiveRecord::Base
  has_many :pets
end


person.pets.destroy(Pet.find(1))
Pet.find(1)
# => ActiveRecord::RecordNotFound: Couldn't find all Pets with 'id': (1)

Last updated

Was this helpful?