0

I'm newish to Rails and working on a project that I would like to create a parent/child relationship using devise. I've looked through a good bit of the literature on Devise, but didn't see any clear cut way to do what I'm trying to accomplish (though it's certainly possible I overlooked the answer because I was using different terminology).

Here's what I'd like to do:

Companies sign up using the normal devise registration flow with a little extra information - i.e. Company name, address, etc. They then add 'users' once inside the application. Users shouldn't have an external sign-up flow. I would like to each user to inherit the company information from Company.

Here is what I thought I'd try:

  1. Generate both the Company and the User devise models.
  2. Generate the User controller, modify the new action to @current_company.user.build

Would this accomplish what I'm trying to do?

Any further reading that you might be able to pass along would be appreciated!

PSCampbell
  • 858
  • 9
  • 27

1 Answers1

0

Do this....

#app/models/company.rb
class Company < ActiveRecord::Base
   has_many :users
end

#app/models/user.rb
class User < ActiveRecord::Base
   devise ....
   belongs_to :company
end

This is a has_and_belongs_to_many association.


What you should be doing is leaving companies to be its own model; don't include Devise on it at all.

Instead, you should make your User model the only one with the authentication. After that, each user will have to be related to a particular company (or if you wanted to use has_many :through, you could have a user a member of many companies).

You'd have to scope the Devise authentication around a company (IE company.users.exists? user); I've been working on that but don't have a thorough implementation yet.

There's a good ref here: Scope login to subdomain

This will allow you to have users for a particular company; which you'll be either be able to scope using subdomains (to make a crude "multi tenant" app), or to have a select box at sign-in or something.


Obviously, your lack of input means I've got to write a broad answer.

If I were you, I'd think about your desired flow.

Research multi tenancy with Rails (the apartment gem is good if you're using PGSQL) - this should give you a better idea on the way the application should work (IE how does a company need to support users).

Richard Peck
  • 76,116
  • 9
  • 93
  • 147