How do I 'validate' on destroy in rails

前端 未结 11 1907
你的背包
你的背包 2020-11-28 06:33

On destruction of a restful resource, I want to guarantee a few things before I allow a destroy operation to continue? Basically, I want the ability to stop the destroy oper

11条回答
  •  青春惊慌失措
    2020-11-28 07:31

    You can raise an exception which you then catch. Rails wraps deletes in a transaction, which helps matters.

    For example:

    class Booking < ActiveRecord::Base
      has_many   :booking_payments
      ....
      def destroy
        raise "Cannot delete booking with payments" unless booking_payments.count == 0
        # ... ok, go ahead and destroy
        super
      end
    end
    

    Alternatively you can use the before_destroy callback. This callback is normally used to destroy dependent records, but you can throw an exception or add an error instead.

    def before_destroy
      return true if booking_payments.count == 0
      errors.add :base, "Cannot delete booking with payments"
      # or errors.add_to_base in Rails 2
      false
      # Rails 5
      throw(:abort)
    end
    

    myBooking.destroy will now return false, and myBooking.errors will be populated on return.

提交回复
热议问题