Strawberry
Strawberry

Reputation: 67968

Sub class models, how I scope the ActiveRecord models?

If I have a user with roles, like so:

class User < ApplicationRecord

class Manager < User

   def after_initialize do |u|
      u.role = User.roles[:manager] if u.new_record?
   end

then this will allow all instances of Manager to automatically have the role populated. However, when I make a call such as Manager.all then this will give me back all instances of user, because it's not initialising Manager. The expected behaviour would be to receive all users with the role manager. What's the best way to go about this?

Upvotes: 0

Views: 1013

Answers (2)

brendandeere
brendandeere

Reputation: 103

If you are subclassing an active record model you might want to implement single table inheritance by adding a type column to the user class.

Docs

This will allow manager objects to automatically be initialized as Manager instances instead of User instances.

This will also allow you to call Manager.all but somewhat removes the need for the roles relationship.

I personally would choose to stick with either the roles relationship, or subclassing the User model, but not both.

Upvotes: 1

buncis
buncis

Reputation: 2513

add this to your user model

scope :manager, -> { where(role: "manager") }

then when you want to call all user with manager role

do this

User.manager

If you still want to use subclass just make it as default scope in your subclass

class Manager < User
  default_scope { where(role: "manager") }
end

Upvotes: 1

Related Questions