本文介绍了在关注中定义的覆盖范围内调用 super的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望将附加查询链接到模型中的范围.范围在关注中定义.
I'm looking to chain an additional query onto a scope in a model. The scope is defined in a concern.
module Companyable
extend ActiveSupport::Concern
included do
scope :for_company, ->(id) {
where(:company_id => id)
}
end
end
class Order < ActiveRecord::Base
include Companyable
# I'd like to be able to do something like this:
scope :for_company, ->(id) {
super(id).where.not(:status => 'cancelled')
}
end
然而,这可以理解地抛出一个 NameError: undefined method 'for_company' for class 'Order'
However, that understandably throws a NameError: undefined method 'for_company' for class 'Order'
推荐答案
这是我想出的解决方案:
Here's the solution I came up with in my case:
而不是 scope
,只需使用常规类方法,因为 scope
只是类方法的语法糖".当您需要使用 super
进行覆盖时,这更容易处理.在您的情况下,它看起来像这样:
Rather than scope
, just go with a regular class method since scope
is just "syntactic sugar" for a class method. This is easier to deal with when you need to override using super
. In your case it would look like this:
module Companyable
extend ActiveSupport::Concern
module ClassMethods
def for_company(id)
where(:company_id => id)
end
end
end
class Order < ActiveRecord::Base
include Companyable
def self.for_company(id)
super(id).where.not(:status => 'cancelled')
end
end
这篇关于在关注中定义的覆盖范围内调用 super的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!