3
votes

I have a Rails app with three kinds of users, professionals, students and regular citizens. I therefore made the User model polymorphic with three different kinds of profiles.

User.rb

belongs_to :profile, polymorphic: true

Professional.rb

 has_one :user, as: :profile, dependent: :destroy

Student.rb

has_one :user, as: :profile, dependent: :destroy

Citizen.rb

has_one :user, as: :profile, dependent: :destroy

I want to use Devise as central sign up and created the devise for the User model

rails generate devise User

and then I created a Registrations controller that inherited from Devise Registrations controller, and in the after_sign_up_path_for method, I assigned the user to whichever of the profiles the user selected on the signup form.

class RegistrationsController < Devise::RegistrationsController
  protected

  def after_sign_up_path_for(user)

    if user.professional === true

      user.profile = ProfessionalProfile.create!
      user.save!
    elsif
       .... 

  end
end

Right now, this works, in that, by overriding the def after_sign_in_path_for(resource) in the Application controller, I can redirect users to whatever profile they created

  def after_sign_in_path_for(resource)

     if current_user.profile_type === 'ProfessionalProfile'
        professional_profile_path(current_user)

     elsif 
        ....
    end

However, even though this works, I have very little experience with Rails (in terms of making my own application; i've followed a few tutorials) and devise, so I'm wondering, before I continue on developing the app, if I'm going to run into problems either with devise or anything else by having created profiles that way. Is there a better way to do this?

I guess as one possible alternative I was wondering if I should try to override Devise's create user action, so that it creates the relevant Profile at the same time.

1
It doesn't look like anyone answered this, do you have any input to add? I'm interested in what you found.stephenmurdoch

1 Answers

1
votes

You can add columns to the user table by using the code:

rails generate migration add_professional_to_users professional:boolean

and similarly

rails generate migration add_student_to_users student:boolean

and also

rails generate migration add_citizen_to_users citizen:boolean

this is a better method according to me as a similar method is described by devise to create an admin, see it here :devise,option1

Similarly you may add these roles. Just an option but one that I feel is better.