Search code examples
ruby-on-railsruby-on-rails-5

Prevent deletion of records where a certain field is non-blank


If I have a Widget model as follows:

create_table "widgets", id: :serial, force: :cascade do |t|
  t.string "name"
  t.integer "quantity"
end

... how do I prevent a destroy action if quantity is something other than nil or zero? I assume this is something I should do in the model rather than the controller?


Solution

  • I have figured it out:

    class Widget < ApplicationRecord
    
      before_destroy :ensure_quantity_blank
    
    protected
    
      def ensure_quantity_blank
        if !self.quantity.blank?
          errors.add(:quantity, "Cannot delete widget with a quantity")
          throw(:abort)
        end
      end
    
    end
    

    See also How do I 'validate' on destroy in rails