我希望将附加查询链接到模型中的范围。范围在关注中定义。
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
Run Code Online (Sandbox Code Playgroud)
然而,这可以理解地抛出一个 NameError: undefined method 'for_company' for class 'Order'
这是我针对我的案例提出的解决方案:
而不是scope,只需使用常规的类方法,因为scope它只是类方法的“语法糖”。当您需要使用 覆盖时,这更容易处理super。在你的情况下,它看起来像这样:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
838 次 |
| 最近记录: |