0

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?

Vasilisa
  • 4,604
  • 3
  • 20
  • 25
MSC
  • 3,286
  • 5
  • 29
  • 47

1 Answers1

1

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

MSC
  • 3,286
  • 5
  • 29
  • 47