Search code examples
ruby-on-railsactiverecordsti

Rails STI overriding scopes


Let's say I have a STI setup as follows:

class User < ActiveRecord::Base
  scope :busy, -> { where('busy_factor > 1') }
end

class HeroUser < User
  scope :busy, -> { where('busy_factor > 5') }
end

So, hero users have a different threshold for the busy scope.

Now, if I do this, I get warnings:

Creating scope :busy. Overwriting existing method HeroUser.busy.

Everything seems to function correctly, but I'm wondering if there's a better way to do this.


Solution

  • A cleaner way would be the following:

    1. Remove scope for descendant models
    2. Introduce a class method (i.e. busy_factor) which would return busy factor for that specific type of models.
    3. Override this class methods in descendants where appropriate.
    4. Rewite the scope in base class as:

      scope :busy, -> { where('busy_factor > ?', self.busy_factor) }

    Hope this helps.