inheritanceactiverecordruby-on-rails-3.2default-scope

Rails: ActiveRecord's default_scope and class inheritance


My app has not only Users but also Admins and SuperAdmins. Since all three share the same attributes i'd like to use only one Table with an additional attribute "role" that can either be "user", "admin" or "super_admin":

class User < ActiveRecord::Base
 # with nickname and password
end


class Admin < User

  def power
    puts "admin rights"
  end
end


class SuperAdmin < Admin

  def superpower
    puts "I've got the #{power}!"
  end
end

Now I want to do something like SuperAdmin.all to get only SuperAdmins. Using a default_scope seems to get me there:

class SuperAdmin < Admin
  default_scope where(["role = ?", "super_admin"])

  # ...
end

Now I'm adding a default_scope to Admin too:

class Admin < User
  default_scope where(["role = ?", "admin"])

  # ...
end

Aaaand... SuperAdmin.all returns nothing anymore. Why is that?


Solution

  • If there is more than one default_scope, ActiveRecord chains them. So SuperAdmin.all looks for Users having role "Admin" AND "SuperAdmin" – which can never happen.

    To get around that you can override the default_scope of the inherited Model, so just define a self.default_scope by yourself:

     class SuperAdmin < Admin
        def self.default_scope
            where(["role = ?", "super_admin"])
        end
        #...
     end
    

    SuperAdmin.all should work as expected now.