简体   繁体   中英

Rails polymorphic user model with Devise

So I know this question has been ask a ton of times but my question goes a little bit further.

When modeling my application I have two types of users that have a polymorphic association to the user model. Such as:

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 an STI, is because User_Type_1 has something like 4 fields and User_Type_2 has something like 20 fields and I didn't want the user table to have so many fields (yes 24-ish fields is not a lot but I'd rather not have ~20 fields empty most of the time)

I understand how this works, my question is I want the sign up form to only be used to sign up users of type User_Type_1 but the sign in form to be used to both. (I will have an admin side of the application which will create users of User_Type_2 )

I know I can use the after_sign_in_path_for(resource) override in AppicationController somehow to redirect to the right part of the site on sign in. Something like:

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 my questions are how would I make the form to work with Devise and only allow signups of type User_Type_1 and then sign them in after sign_up?

Also, if I am going about this the wrong way, what is the right way?

I was able to answer my own question and am putting it here so that maybe it can help someone else with the same problem.

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

I realized the answer to the form question as typing it out here:

I just created a normal form for the User_Type_1 with nested attributes for User and had it post to the UserType1Controller Then saved both objects and called the sign_in_and_redirect helper 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 it was all good.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM