用Devise创建Rails多态用户模型

jef*_*cco 4 ruby-on-rails polymorphic-associations devise

所以我知道这个问题已被问了很多次,但我的问题更进一步.

在为我的应用程序建模时,我有两种类型的用户,它们与用户模型具有多态关联.如:

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
Run Code Online (Sandbox Code Playgroud)

我这样做的原因,而不是STI,是因为User_Type_1有4个字段,User_Type_2有20个字段,我不希望用户表有这么多字段(是的24-ish字段不是很多,但我'大多数时候,我宁愿没有20个字段空了)

我理解这是如何工作的,我的问题是我希望注册表单只用于注册类型的用户,User_Type_1但签名表单用于两者.(我将有一个应用程序的管理员端,将创建用户User_Type_2)

我知道我可以after_sign_in_path_for(resource)AppicationController某种方式使用覆盖在登录时重定向到网站的右侧部分.例如:

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
Run Code Online (Sandbox Code Playgroud)

所以我想我的问题是如何让表单与Devise一起工作,只允许注册类型User_Type_1然后在sign_up之后签名?

另外,如果我以错误的方式解决这个问题,那么正确的方法是什么?

jef*_*cco 5

我能够回答我自己的问题并将其放在这里,以便它可以帮助其他人解决同样的问题.

登录问题很简单,只需使用默认的设计登录和上面所述的after_sign_in_path_forinApplicationController

我在这里输入了表格问题的答案:

我刚刚为User_Type_1嵌套属性创建了一个普通表单,User 并将其发布到UserType1Controller Then保存了两个对象并sign_in_and_redirect从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
Run Code Online (Sandbox Code Playgroud)

然后after_sign_in_path_for从上面的方法将它发送到正确的地方,这一切都很好.