Reputation: 841
I am using devise for authentication and finding a way to get out of this.
Can I explore same design user having multiple roles ?. So that he can login as Teacher or Parent both?. Basically he can switch accounts like 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 above fields, if user is logging in as 'Teacher' and its ID.
Upvotes: 4
Views: 810
Reputation: 102443
You can add a polymorphic has_many
relationship:
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
Upvotes: 2