How to manage multiple roles using polymorphic association in rails?

I am using a program to authenticate and am finding a way to get out of this.

Can I explore the same user who has multiple roles? So that he can enter as Teacher or Parent? Basically it can switch accounts, for example multiple roles.

class User < ActiveRecord
  belongs_to :loginable, polymorphic: true
end

class Parent < ActiveRecord
  has_one :user, as: :loginable
end

class Teacher < ActiveRecord
  has_one :user, as: :loginable
end


for eg: loginable_type: "Parent", loginable_id: 123

      

I want to find a way to change the above fields if the user is logged in as "Teacher" and his ID.

+3


source to share


1 answer


You can add a polymorphic relationship has_many

:



class CreateUserRoles < ActiveRecord::Migration
  def change
    create_table :user_roles do |t|
      t.integer :role_id
      t.integer :user_id
      t.string  :role_type # stores the class of role
      t.timestamps
    end
    add_index :user_roles, [:role_id, :role_type]
  end
end

class AddActiveRoleToUser < ActiveRecord::Migration
  def change
    change_table :user_roles do |t|
      t.integer :active_role_id
      t.timestamps
    end
  end
end

class User < ActiveRecord
   has_many :roles, polymorphic: true
   has_one :active_role, polymorphic: true


   def has_role? role_name
     self.roles.where(role_type: role_name).any?
   end
end

      

+2


source







All Articles