3

I'm using Ruby on Rails 3.2.8 with Sorcery authentication.

What is the best way to create sub-users accounts?

Ideally, I would like to invite members by email and have them click on a link and they choose their username/password. Is it possible to do this within the same user table so they all can login from the same login page?

To wrap your head around what I'm trying to do is... Employer can add/invite employees to join the system and any data input to the system will belong to the employer.

Michael
  • 115
  • 1
  • 6

1 Answers1

1

Personally I would handle this as a single table inheritance model with a same-table association column.

Put a field called boss_id on your users table. You'll have the main User model, that has the Sorcery authentication stuff and any common logic. Underneath it you have Employer and Employee. They have a method called boss: for the employer, this returns self or nil (whichever you find makes most sense), whereas for employees, this is an actual association method, something like this:

class Employee < User
  belongs_to :boss, class_name: 'User'

end

When an employer sends out an invitation, direct the invitees to a URL for invitations specific to the employer, like:

http://yoursite.com/employer/3/invitation

When the user creates their account you associate them to their owning employer.

When an employer views their data, ensure that you pull their child employees' data as well, using the users table as a join table:

class Employer < User
  has_many :employees, class_name: 'User', foreign_key: 'boss_id'

  has_many :contacts # Or whatever your application-specific stuff is 
    # that you want employers to see through their employees
  has_many :employee_contacts, through: :employees, source: :contacts
end

If you need to assign ownership to employers in the database, I'd use an observer to watch for saves on the owned models, and if they are saved by someone with a boss, set an additional column to that boss' ID.

Veraticus
  • 15,944
  • 3
  • 41
  • 45