Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling super in overriden scope defined in concern

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

However, that understandably throws a NameError: undefined method 'for_company' for class 'Order'

like image 368
Abraham Chan Avatar asked Nov 10 '22 19:11

Abraham Chan


1 Answers

Here's the solution I came up with in my case:

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
like image 143
sixty4bit Avatar answered Jan 04 '23 02:01

sixty4bit