Ruby on Rails:存在表名时禁用`delete_all`

发布于 2025-01-26 23:59:43 字数 381 浏览 3 评论 0原文

delete_all很有用,但是我永远不想在同一行上看到它,带有表名。我想在控制台和代码中禁用tablename.destroy_all之类的内容。

本月早些时候发生的一个有趣的问题是:

application.destroy_all在模型上而不是applications.destroy_all在模型上调用。 (模型HAS_MANY应用程序)

对于新手ROR的人来说,它看起来非常相似,但是结果是灾难性的。

我对某种形式的棉/代码样式工具开放,但这确实不会在控制台方案中捕捉到它。 (另外,我无法让Rubo-cop做类似的事情),

基本上,我要求一种使游戏机和代码库更安全的方法桌子。

delete_all is useful, but I never want to see it called on the same line with a table name. I'd like to disable things like TableName.destroy_all in both console and code.

One interesting issue happened earlier this month:

Application.destroy_all was called on a model instead of applications.destroy_all
(the model has_many applications)

For somebody new to ROR, it looks very similar, but the results were disastrous.

I'm open to some form of lint/code style tool, but that really wouldn't catch it in the console scenario. (Plus, I haven't been able to get rubo-cop to do something like this yet)

Basically, I'm asking for a way to make the console and codebase more secure so that newer developers can't inadvertantly delete everything in a table.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

人生戏 2025-02-02 23:59:43

我并不完全清楚您要完成的工作,但是您可以尝试使用类似的东西在applicationmodel中覆盖方法(假设Rails 5或更高,或其他存在的根模型) 。

class ApplicationModel < ActiveRecord::Base
  def self.destroy_all(*args)
    raise('Cannot destroy all records of a model this way. Did you mean to delete a subset of records instead?')
  end
end

如果您想更难运行的话,可能会将这种方法私有化...

def self.destroy_all(*args)
  raise('Cannot destroy all records of a model this way. Did you mean to delete a subset of records instead?')
end
private_class_method :destroy_all

您可能会很喜欢,并允许您检查一下您检查的特殊参数,但请尝试一下,看看它是如何进行的。

I'm not entirely clear on what you are trying to accomplish, but you could try overriding the method in your ApplicationModel with something like this (assuming Rails 5 or greater, or otherwise a root model in existence).

class ApplicationModel < ActiveRecord::Base
  def self.destroy_all(*args)
    raise('Cannot destroy all records of a model this way. Did you mean to delete a subset of records instead?')
  end
end

Possibly make this method private if you'd like it even harder to run...

def self.destroy_all(*args)
  raise('Cannot destroy all records of a model this way. Did you mean to delete a subset of records instead?')
end
private_class_method :destroy_all

You could get fancy and allow this to be bypassed with a special argument that you check for, but give this a try and see how it goes.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文