Rubies on rails with different types of users

I am trying to create an application with different types of users, I use authlogic to authenticate users.

So, I have one user model that has the necessary field for authlogic to do its magic. Now I want to add a couple of different models that would describe additional fields for different users.

Let's say that the user is registered, then he will choose his type of user, when he is registered, he will be able to add information specific to his user model.

What would be the best way to do this? I am currently looking at polymorphic models, but I'm not sure what the best route is for this. Any help would be greatly appreciated, thanks.

+1
source share
2 answers

You can create different tables profileand just bind the profile to the user. Therefore, for each type of user, you can create a table and save certain information there and have a column user_idto return to users.

class User < ActiveRecord::Base
  has_one :type_1
  has_one :type_2
end

class Type1 < ActiveRecord::Base
  belongs_to :user
end

class Type2 < ActiveRecord::Base
  belongs_to :user
end

Now this is not very DRY and can lead to problems if you constantly add user types. So you can study polymorphism.

Polymorphism table usersdetermines the type of user ( profileable_idand profileable_type). So something like this:

class User < ActiveRecord::Base
  belongs_to :profileable, :polymorphic => true
end

class Type1 < ActiveRecord::Base
  has_one :user, :as => :profileable
end

class Type2 < ActiveRecord::Base
  has_one :user, :as => :profileable
end

STI ( ) . , .

+5

Source: https://habr.com/ru/post/1782366/


All Articles