gpt4 book ai didi

ruby-on-rails - 如何使用新方法扩展 ActiveRecord 关系?

转载 作者:行者123 更新时间:2023-12-04 07:38:19 25 4
gpt4 key购买 nike

假设我有这样的简单 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 中正确的方法是什么?在所有这种情况下,我如何访问当前关系?

最佳答案

我试图将代码包含到动态添加到任何 AR 类中的 ActiveRecord_Relation 类中。

如果您需要将 .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

关于ruby-on-rails - 如何使用新方法扩展 ActiveRecord 关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34729332/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com