You can create an exception, which you then catch. Rails wraps deletes transactions, which helps.
For example:
class Booking < ActiveRecord::Base has_many :booking_payments .... def destroy raise "Cannot delete booking with payments" unless booking_payments.count == 0
Alternatively, you can use the before_destroy callback. This callback is usually used to destroy dependent records, but you can throw an exception or add an error.
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 when it returns.
Airsource Ltd 23 Sep '08 at 19:22 2008-09-23 19:22
source share