gpt4 book ai didi

ruby-on-rails-4 - 在关注中定义的覆盖范围内调用 super

转载 作者:行者123 更新时间:2023-12-03 17:18:24 25 4
gpt4 key购买 nike

我希望将附加查询链接到模型中的范围。范围在关注中定义。

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'

最佳答案

这是我在案例中提出的解决方案:

而不是 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

关于ruby-on-rails-4 - 在关注中定义的覆盖范围内调用 super,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28449044/

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