Rails:如何防止删除记录? [英] Rails: How to prevent the deletion of records?

查看:39
本文介绍了Rails:如何防止删除记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型国家,因此有一个表格国家.国家表作为 iso 国家和货币代码的集合,不应减少其中的内容(在我用种子数据填充它之后).因为 Country 是 ActiveRecord::Base 的子类,所以它继承了诸如 destroy、delete_all 等删除记录的类方法.我正在寻找一种解决方案来防止在模型级别删除记录.

I have a model Country and therefore a table countries. The countries table act as a collection of iso country and currency codes and should never reduce there content (after I have filled it with seed data). Because Country is a subclass of ActiveRecord::Base it inherits class methods like destroy, delete_all and so forth which deletes records. I'm looking for a solution to prevent the deletion of records at the model level.

办公室.我知道我可以使用面向对象的方法通过覆盖这些方法来解决这个问题(并在调用时引发例如错误),但这假设我必须知道基类的所有继承方法.如果有人可以提供更优雅的解决方案,我会很高兴.

Ofc. I know that I can make use of the object oriented approach to solve this problem by overriding this methods (and raise for instance an error when they called), but this assumes that I have to know all the inherited methods of the base class. I would be glad if someone could offer a more elegant solution.

推荐答案

从 Mark Swardstrom 的回答中汲取灵感,我提出以下同样适用于 Rails 的方案 >5.0:

Taking inspiration from Mark Swardstrom answer, I propose the following that is working also on Rails > 5.0:

在您的模型中:

before_destroy :stop_destroy

def stop_destroy
  errors.add(:base, :undestroyable)
  throw :abort
end

以下将使所有对 model.destroy 的调用返回 false 并且您的模型不会被删除.

The following will make all calls to model.destroy return false and your model will not be deleted.

您可以争辩说,对 model.delete 的调用仍然有效,并会删除您的记录,但由于这些是较低级别的调用,这对我来说完全有意义.

You can argue that still, calls to model.delete will work, and delete your record, but since these are lower level calls this makes perfectly sense to me.

如果需要,您也可以直接从数据库中删除记录,但上述解决方案会阻止从应用程序级别删除记录,这是检查这一点的正确位置.

You could also delete the records directly from the database if you want, but the above solution prevents deletion from the application level, which is the right place to check that.

Rubocop 检查您对 delete 或 delete_all 的调用并发出警告,因此您可以 100% 确定如果您调用 model.delete 是因为您真的想要它.

Rubocop checks your calls to delete or delete_all and raises a warning, so you can be 100% sure that if you call model.delete is because you really want it.

我的解决方案适用于需要 throw :abort 而不是返回 false 的最新 Rails 版本.

My solution works on latest Rails versions where you need to throw :abort instead of returning false.

这篇关于Rails:如何防止删除记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆