Rails polymorphic user model with design

So, I know that this question has been asked a ton of times, but my question goes a little further.

When modeling my application, I have two types of users that have a polymorphic relationship with the user model. For instance:

class User < ActiveRecord::Base belongs_to :profileable, :polymorphic => true end class User_Type_1 < ActiveRecord::Base has_one :user, :as => :profileable end class User_Type_2 < ActiveRecord::Base has_one :user, :as => :profileable end 

The reason I did this, instead of STI, is because User_Type_1 has something like 4 fields, and User_Type_2 has something like 20 fields, and I did not want the user table to have so many fields (yes 24 - ish there are not many fields, but I would prefer not to have ~ 20 fields empty most of the time)

I understand how this works, my question is that I want the registration form to be used only for registering users of type User_Type_1 , but in the form of a sign that will be used for both. (I will have the admin part of the application that will create users User_Type_2 )

I know that I can use the after_sign_in_path_for(resource) override in the AppicationController to redirect to the right side of the site upon login. Sort of:

 def after_sign_in_path_for(resource) case current_user.profileable_type when "user_type_1" return user_type_1_index_path when "user_type_2" return user_type_1_index_path end end 

So, I guess that my questions are about how I can make a form for working with Devise and allow registration of type User_Type_1 , and then sign them after sign_up?

Also, if I'm going to do it wrong, is that the right way?

+4
source share
1 answer

I was able to answer my question and put it here, so that perhaps he would help someone else with the same problem.

The login problem was simple, just use the default registration and after_sign_in_path_for in the ApplicationController as described above

I understood the answer to the form question by typing it here:

I just created a normal form for User_Type_1 with nested attributes for User and whether he sent a message to UserType1Controller Then I saved both objects and called the sign_in_and_redirect from Devise

 class UserType1Controller < ApplicationController ... def create @user = User.new(params[:user]) @user_type_1 = UserType1.new(params[:patron]) @user.profileable = @user_type_1 @user_type_1.save @user.save sign_in_and_redirect @user end ... end 

Then the after_sign_in_path_for method from above sent it to the right place, and everything was fine.

+5
source

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


All Articles