【问题标题】:Calling super in overriden scope defined in concern在关注中定义的覆盖范围内调用 super
【发布时间】:2015-02-11 07:45:17
【问题描述】:

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

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'

【问题讨论】:

  • 你有没有找到办法做到这一点?
  • @sixty4bit 抱歉,没有
  • 好的,当我遇到你的问题时,我早些时候正在努力解决这个问题。我已经发布了我的想法,以防对您有帮助。

标签: ruby-on-rails-4


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2019-11-11
    • 2014-02-04
    • 2022-11-11
    • 1970-01-01
    • 1970-01-01
    • 2019-11-03
    • 2016-09-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多