Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 879
Aaron Gibralter Avatar asked Feb 19 '23 13:02

Aaron Gibralter


1 Answers

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.

like image 118
Anton Avatar answered Feb 27 '23 00:02

Anton