Delete & destroy association
delete 沒有
dependent: :destroy只清空*_iddelete 有
dependent: :destroy皆刪除recorddestroy 不論有無
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?