5

I have installed Devise and created Users and also Admins using Option 1 from this tutorial https://github.com/plataformatec/devise/wiki/How-To:-Add-an-Admin-role

Now I need a little help. When adding the Admins it creates a different table, and the potential arises that the admins and regular users could have the same ID's.

So how exactly do I got about grabbing information from users and admins? Say for example I want to display all users? Do I have to traverse the users table and then the admins table?

Or if I am displaying a post. How will I know which table to look for to get the user or admin info?

I know I can just add a role column to the users table but I wanted to avoid this.

I hope this makes sense haha

Cœur
  • 37,241
  • 25
  • 195
  • 267
Dan
  • 2,299
  • 2
  • 20
  • 41

1 Answers1

16

I highly recommend using the Single Table Inheritance (STI). You could do the STI by adding a column named type with a string datatype in the users table and create an admin model as well as a normal_user model both models will inherit from the user model of the devise gem.

class NormalUser < User
end

class Admin < User
end

The type column is a reserved word which will hold a value either NormalUser or Admin according to the user type you created.

To create an admin use Admin.create(...) and to create a normal user use NormalUser.create(...) where the dots are the attributes of the Admin and the NormalUser

d_rail
  • 4,109
  • 32
  • 37
mohamagdy
  • 2,093
  • 2
  • 17
  • 22
  • @mohammed.magdy Awesome I think this is what I was looking for. Could you help me in setting up the proper authentication code. I am attempting to use Rails_Admin so I need a way to authenticate admins. – Dan Feb 27 '12 at 01:10
  • 3
    Sure, in the users table, you added a column named type which is a string datatype. The value of the type column will be either Admin or NormalUser (in our case here). When a user is logged in, you could get the type of the user by adding a method in the user.rb that checks the signed in user type. For the admin define a method named admin? the body will be self.is_a?(Admin) this will return true if the signed in user is admin else will return false. Same for the NormalUser, in the user.rb file add a method named def normal_user? the body of the method will be self.is_a?(NormalUser). – mohamagdy Feb 27 '12 at 08:50
  • For Authentication, I recommend using cancan gem but the devise will work for you in both authorization and authentication if the roles are not too much. – mohamagdy Feb 27 '12 at 08:51
  • great thanks alot for your help. I have successfully created the STI and am working on setting up authorization. – Dan Feb 27 '12 at 20:35