我基本上想要以下功能,但反过来,我已经有了 undestroy
适用于单个类的函数。
但是,我试图扩展 ActiveRecord::Relation 但无济于事。以下是我如何通过 for ActiveRecord::Base
为其他方法做的
ActiveRecord::Base.extend Track::BaseTrack
但使用 ActiveRecord::Relation.extend Track::TrackRelation
似乎什么也没做。模块TrackRelation
(在 Track
内)是:
module TrackRelation
def undestroy_all(conditions = nil)
if conditions
where(conditions).undestroy_all
else
to_a.each {|object| object.undestroy }.tap { reset }
end
end
end
我是否为关系使用了正确的 ActiveRecord 类?
错误是:
undefined method "undestroy_all" for #<ActiveRecord::Relation []>
最佳答案
当您调用 ActiveRecord::Relation.extend Track::TrackRelation
时,您正在将 Track::TrackRelation
方法混合到 ActiveRecord::Relation
作为类方法。
您要做的是混合使用与实例方法相同的方法。您可以使用 include
而不是 extend
来做到这一点。但是 Module#include
是私有(private)的。所以实现你想要的一种方法是:
ActiveRecord::Relation.send(:include, Track::TrackRelation)
关于ruby-on-rails - RoR 扩展 ActiveRecord::relation with undestroy_all,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17946852/