How do I 'validate' on destroy in rails

前端 未结 11 1912
你的背包
你的背包 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:35

    You can wrap the destroy action in an "if" statement in the controller:

    def destroy # in controller context
      if (model.valid_destroy?)
        model.destroy # if in model context, use `super`
      end
    end
    

    Where valid_destroy? is a method on your model class that returns true if the conditions for destroying a record are met.

    Having a method like this will also let you prevent the display of the delete option to the user - which will improve the user experience as the user won't be able to perform an illegal operation.

提交回复
热议问题