【问题标题】:How can I extend ActiveRecord relations with new method?如何使用新方法扩展 ActiveRecord 关系?
【发布时间】:2016-04-16 05:20:01
【问题描述】:

假设我有这样的简单 ActiveRecord 模型:

class Post < ActiveRecord::Base
  belongs_to :category
end

class Category < ActiveRecord::Base
  has_many :posts
  has_many :published_posts, -> { where(:published => true) }
end

我想创建模块Reindexable,它将一个名为reindex 的方法添加到基类中。我希望能够通过以下 3 种方式调用此方法:

Place.reindex
Place.reindex(Place.where(:published => true))
Place.where(:published => true).reindex
Category.first.places.reindex

在这个方法里面我应该可以做这样的事情:

Reindexer.new(relation).reindex # how can I get relation here?

在 Ruby-on-Rails 中正确的做法是什么?在这种情况下如何访问当前关系?

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    我尝试将代码包含到 ActiveRecord_Relation 类中,该类会动态添加到任何 AR 类中。

    如果您需要将 .to_csv 添加到 MyModel.all.to_csv 等所有调用中:

    型号:

    class MyModel < ActiveRecord::Base
      include ToCsv
    end
    

    您想要包含的模块

    module ToCsv
      extend ActiveSupport::Concern
    
      #  Dynamically including our Relation and extending current class
      #
      def self.included(child_class)
        child_class.const_get('ActiveRecord_Relation').include(RelationMethods)
        child_class.extend(ExtendMethods)
      end
    
      #  Instance Method
      #
      def to_csv(opts = {})
      end
    
      #  Module containing methods to be extended into the target
      #
      module ExtendMethods
    
        #  Allowing all child classes to extend ActiveRecord_Relation
        #
        def inherited(child_class)
          super + (child_class.const_get('ActiveRecord_Relation').include(RelationMethods) ? 1 : 0 )
        end
      end
    
      #  Holds methods to be added to relation class
      #
      module RelationMethods
        extend ActiveSupport::Concern
    
        #  Relation Method
        #
        def to_csv(opts = {})
        end
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-28
      • 1970-01-01
      • 1970-01-01
      • 2023-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多