【问题标题】:RoR extend ActiveRecord::relation with undestroy_allRoR 使用 undestroy_all 扩展 ActiveRecord::relation
【发布时间】:2013-07-30 12:19:03
【问题描述】:

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

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

但是,我试图扩展 ActiveRecord::Relation 无济于事。以下是我对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 []>

【问题讨论】:

    标签: ruby-on-rails ruby activerecord


    【解决方案1】:

    当您调用ActiveRecord::Relation.extend Track::TrackRelation 时,您将Track::TrackRelation 方法作为类方法混合到ActiveRecord::Relation 中。

    您想要做的是混合使用与实例方法相同的方法。您可以使用include 而不是extend 来做到这一点。但是Module#include 是私有的。因此,实现您想要的一种方法是:

    ActiveRecord::Relation.send(:include, Track::TrackRelation)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-14
      • 1970-01-01
      相关资源
      最近更新 更多