Polymorphic association for multi-type registration in rails

I am using an application authentication program. I have a User model that is an input / output model.

The functionality is that when the client, that is, the user subscribes, he will be busy to fill out the page of the required user profile. Everything worked perfectly through development.

Now I have new functionality. The user can be of different types (say A , B , C )

If the user is of type A , he must follow the same registration process and the same profile page.

If the user is of type B , then the registration screen is different and awaits confirmation from the administrator. Various changes for type C too.

All different types have different profile pages, and the fields are different.

So, I decided to have a polymorphic association, and that's exactly how my models look.

 class User < ActiveRecord::Base devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable attr_accessible :email, :password, :password_confirmation, :remember_me belongs_to :user_type, :polymorphic => true end class A has_one :user, :as => :user_type end class B has_one :user, :as => :user_type end class C has_one :user, :as => :user_type end 

I just want to know that this is the right way to go the script or is there a better way to implement this?

+4
source share
2 answers

You want to use the Rails' type magic post.

 # user.rb class User < ActiveRecord::Base # create_table 'users' do |t| # t.string :name # t.string :type # end end # user_a.rb class UserA < User end # user_b.rb class UserB < User end # user_c.rb class UserC < User end 

 UserA.create(name: "bricker") user_a = User.where(type: "UserA").first same_user_a = UserA.all.first user_a == same_user_a #=> true user_a.class #=> UserA user_a.is_a? User #=> true 

Update

 class UserLogin < ActiveRecord::Base # create_table :user_logins do |t| # t.integer :user_id # t.string :user_type # t.string :login # t.string :encrypted_password # end # devise ... belongs_to :user, polymorphic: true end class User < ActiveRecord::Base self.abstract_class = true has_one :user_login, as: :user end class Admin < User # create_table :admins do |t| # t.integer :user_login_id # t.string :admin_name # end end class Moderator < User # create_table :moderators do |t| # t.integer :user_login_id # t.string :moderator_name # end end 
+1
source

I was in the same

I would strongly advise using non-polymorphic separate models and sharing common functionality with mixins.

I had the same setup that you described, and she had to reorganize it later, as it became really bloated and complicated as the project developed.

+1
source

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


All Articles