ruby-on-rails - RoR 扩展 ActiveRecord::relation with undestroy_all

标签 ruby-on-rails ruby activerecord

我基本上想要以下功能,但反过来,我已经有了 undestroy适用于单个类的函数。

https://github.com/rails/rails/blob/2ad168ee41d590bd9a4d15eddf3c2f719c23b60a/activerecord/lib/active_record/relation.rb#L364

但是,我试图扩展 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/

相关文章:

ruby-on-rails - 更改 rails text_field 表单构建器类型

ruby-on-rails - Rails after_save 和 after_commit 回调

mysql - Rails 迁移似乎已完成,但 rake 仍将迁移显示为挂起

ruby-on-rails - ActiveRecord 使用 JSON 而不是 YAML 进行序列化

ruby-on-rails - 如何使用rails通过postfix邮件服务器发送邮件?

ruby - 使用 headless chrome 和 watir webdriver

ruby - || 之间有什么不同?和救援?

ruby - 在 ruby​​ 中解析一个非常特殊的字符串结构(棒球数据)

ruby-on-rails - Rails AR 日期范围查询 - 夏令时 - 重叠

ruby-on-rails - 这种弃用方法如何工作?