Ruby 在 Rails 上:当存在 table 名称时禁用 `delete_all`
Ruby On Rails: Disable `delete_all` when table name is present
delete_all 很有用,但我不想看到它在同一行上用 table 名称调用。我想在控制台和代码中禁用 TableName.destroy_all
之类的东西。
本月早些时候发生了一个有趣的问题:
在模型上调用了 Application.destroy_all
而不是 applications.destroy_all
(模型 has_many 申请)
对于刚接触 ROR 的人来说,它看起来非常相似,但结果却是灾难性的。
我对某种形式的 lint/code 风格的工具持开放态度,但在控制台场景中确实无法捕捉到它。 (另外,我还没能让 rubo-cop 做这样的事情)
基本上,我要求的是一种使控制台和代码库更安全的方法,这样新开发人员就不会无意中删除 table 中的所有内容。
我不完全清楚你想要完成什么,但你可以尝试用这样的东西覆盖你 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
您可能会喜欢并允许使用您检查的特殊参数绕过它,但请尝试一下,看看效果如何。
delete_all 很有用,但我不想看到它在同一行上用 table 名称调用。我想在控制台和代码中禁用 TableName.destroy_all
之类的东西。
本月早些时候发生了一个有趣的问题:
在模型上调用了Application.destroy_all
而不是 applications.destroy_all
(模型 has_many 申请)
对于刚接触 ROR 的人来说,它看起来非常相似,但结果却是灾难性的。
我对某种形式的 lint/code 风格的工具持开放态度,但在控制台场景中确实无法捕捉到它。 (另外,我还没能让 rubo-cop 做这样的事情)
基本上,我要求的是一种使控制台和代码库更安全的方法,这样新开发人员就不会无意中删除 table 中的所有内容。
我不完全清楚你想要完成什么,但你可以尝试用这样的东西覆盖你 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
您可能会喜欢并允许使用您检查的特殊参数绕过它,但请尝试一下,看看效果如何。