Ruby/Rails syntax
  • Index
  • chap 1
  • chap 2
  • chap 3
  • chap 4
  • Enterprise Rails - big picture
  • Nokogiri
  • ActiveRecord - 進階功能
  • pack & unpack
  • performance
  • rails engine
  • jsonb / json / hstore
  • Deploy
  • Polymorphism/Polymorphic Associations
  • relationship
  • rvm / ENV
  • Auth
  • DB related
  • TODO N+1
  • SQL view
  • module
  • api + create-react-app
  • ONE_LINE
  • Delete & destroy association
Powered by GitBook
On this page
  • delete
  • destroy

Was this helpful?

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)
PreviousONE_LINE

Last updated 5 years ago

Was this helpful?