[英]What's the best way to conditionally override ActiveRecord's deletion mechanism?
I am trying to hijack Rails' deletion mechanism to make it behave differently for a certain set of models. 我正在尝试劫持Rails的删除机制,以使其对某些模型的行为有所不同。
Both ActiveRecord::Base#delete
and #destroy
lead back to ActiveRecord::Relation#delete_all
, so it would make sense to override this method. ActiveRecord::Base#delete
和#destroy
返回到ActiveRecord::Relation#delete_all
,因此可以重写此方法。
I have tried... 我努力了...
class MyModel < ActiveRecord::Base
class << all
def delete_all
"My destruction mechanism"
end
end
end
... but ::all
is a method that returns a different object every time... ...但是
::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
... but ::all
isn't the only scope that needs it overridden anyway... ...但是
::all
并不是唯一需要覆盖它的作用域...
class ActiveRecord::Relation
def delete_all(*args)
"My destruction mechanism"
end
end
... but it can only apply to MyModel and its subclasses... ...但是它只能应用于MyModel及其子类...
class ActiveRecord::Relation
def delete_all(*args)
if @klass.new.is_a?(MyModel)
"My destruction mechanism"
else
super
end
end
end
... but this causes stack overflows on other models. ...但是这会导致其他模型上的堆栈溢出。
Help? 救命?
Overriding delete
and destroy
on your model should accomplish most of what you want. 在模型上重写
delete
和destroy
应该可以完成您想要的大部分工作。 Check out how the Paranoia gem accomplishes its overriding. 了解Paranoia宝石如何实现其压倒性。 The library's only 200 lines or so, and also handles associated models (eg when you have
dependent: :destroy
). 该库只有200行左右,并且还可以处理关联的模型(例如,当您具有
dependent: :destroy
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.