How do I find out why I couldn't #destroy() a record?

前端 未结 5 1162
陌清茗
陌清茗 2021-02-01 15:16
person = Person.find(4123)
person.destroy #=> false

What ways do I have to find out why the record wasn\'t deleted? The model has two validations, b

5条回答
  •  失恋的感觉
    2021-02-01 15:50

    I've run into this a few times now, and have finally come across a simple means of identifying the reason the record was not destroyed (tested in Rails 5.x).

    Simply wrap the call to destroy! in a rescue block, and look at error.record.errors.

    begin
      person = Person.find(4123)
      person.destroy! #=> Note the exclamation mark which will cause an error if it fails
    rescue ActiveRecord::RecordNotDestroyed => error
      puts "errors that prevented destruction: #{error.record.errors}"
    end
    

提交回复
热议问题