我有模型Gateway
和GatewayType
一个范围,我找定义在运行时
Gateway.<gateway_type.name> # => Gateway.where(:gateway_type_id => gateway_type.id)
现在这个<gateway_type.name>
范围应在运行时生成,类似于在运行时添加类/实例级别的方法使用defined_method像下面
class Object
def metaclass
class << self
self
end
end
end
# adding class level methods
GatewayType.all.each do |type|
# adding methods to Gateway
Gateway.metaclass.class_eval do
define_method "all_#{type.name}" do
Gateway.where(:gateway_type_id => type.id)
end
end
end
我不想去与上面的方法,因为它不会让我在where
或其他范围之间添加all_xyzs
像
Gateway.scope1.all_xyzs.scope2
那么......有没有办法在运行时定义scope
?
你是对的,但仍然是原因,1)我想知道我们是否可以在运行时添加范围,2)我希望看到类似“Gateway.scope1.xyzs.scope2”的代码。 –
是的,您可以在运行时添加范围。只需调用类'scope'方法,你想一个范围增加。 –