![](/img/trans.png)
[英]What's the proper way to override Rails ActiveRecord creation/deletion events in a subclass, such as after_create
[英]What's the best way to conditionally override ActiveRecord's deletion mechanism?
我正在尝试劫持Rails的删除机制,以使其对某些模型的行为有所不同。
ActiveRecord::Base#delete
和#destroy
返回到ActiveRecord::Relation#delete_all
,因此可以重写此方法。
我努力了...
class MyModel < ActiveRecord::Base
class << all
def delete_all
"My destruction mechanism"
end
end
end
...但是::all
是每次都会返回不同对象的方法...
class MyModel < ActiveRecord::Base
def self.all
super.tap do |obj|
class << obj
def delete_all
"My destruction mechanism"
end
end
end
end
end
...但是::all
并不是唯一需要覆盖它的作用域...
class ActiveRecord::Relation
def delete_all(*args)
"My destruction mechanism"
end
end
...但是它只能应用于MyModel及其子类...
class ActiveRecord::Relation
def delete_all(*args)
if @klass.new.is_a?(MyModel)
"My destruction mechanism"
else
super
end
end
end
...但是这会导致其他模型上的堆栈溢出。
救命?
在模型上重写delete
和destroy
应该可以完成您想要的大部分工作。 了解Paranoia宝石如何实现其压倒性。 该库只有200行左右,并且还可以处理关联的模型(例如,当您具有dependent: :destroy
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.