How do I 'validate' on destroy in rails

2019-01-06 12:52发布

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 operation if I note that doing so would place the database in a invalid state? There are no validation callbacks on a destroy operation, so how does one "validate" whether a destroy operation should be accepted?

10条回答
Juvenile、少年°
2楼-- · 2019-01-06 13:43

You can also use the before_destroy callback to raise an exception.

查看更多
孤傲高冷的网名
3楼-- · 2019-01-06 13:43

I was hoping this would be supported so I opened a rails issue to get it added:

https://github.com/rails/rails/issues/32376

查看更多
干净又极端
4楼-- · 2019-01-06 13:44

I have these classes or models

class Enterprise < AR::Base
   has_many :products
   before_destroy :enterprise_with_products?

   private

   def empresas_with_portafolios?
      self.portafolios.empty?  
   end
end

class Product < AR::Base
   belongs_to :enterprises
end

Now when you delete an enterprise this process validates if there are products associated with enterprises Note: You have to write this in the top of the class in order to validate it first.

查看更多
戒情不戒烟
5楼-- · 2019-01-06 13:45

It is what I did with Rails 5:

before_destroy do
  cannot_delete_with_qrcodes
  throw(:abort) if errors.present?
end

def cannot_delete_with_qrcodes
  errors.add(:base, 'Cannot delete shop with qrcodes') if qrcodes.any?
end
查看更多
登录 后发表回答