如何通过抽象活动记录向子类添加范围 [英] how can I add a scope to subclass class through abstract active record
本文介绍了如何通过抽象活动记录向子类添加范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想要一些子类,它们都应该有一个范围(同名).虽然我知道直接继承是不可能的,但基本思想如下:
I would like to have a few subclasses that should all have a scope (of the same name). Although I know this is not possible with straight inheritance the basic idea is the following:
class MySuperClass << ActiveRecord::Base
abstract_class = true
scope :scopeForAllSubclasses , lambda {|my_var| where(:var => my_var )}
end
class Subclass1 << MySuperClass
#has attribute var
end
class Subclass2 << MySuperClass
# has attribute var
end
所以现在我想打电话
Subclass1.scopeForAllSubclasses123).all
和
Subclass2.scopeForAllSubclasses(123).all
重点是我想要一组类,它们都通过设计实现了这个范围,而不仅仅是因为开发人员决定这样做.
The whole point it that I want a group of classes that all have implemented this scope by design rather than just because the developer decided to do so.
有什么想法吗?
推荐答案
你可以使用 mixin 而不是超类来做到这一点:
You could do this with a mixin instead of a superclass:
module ScopeBuddy
def self.included base
base.instance_eval "scope :scopeForAllSubclasses , lambda {|my_var| where(:var => my_var )}"
end
end
class ClassA
include ScopeBuddy
end
class ClassB
include ScopeBuddy
end
这会将作用域注入到每个实例中.
This will inject the scope into each instance.
这篇关于如何通过抽象活动记录向子类添加范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文