用Devise创建Rails多态用户模型

时间:2012-03-04 18:17:05

标签: ruby-on-rails devise polymorphic-associations

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

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

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

我这样做的原因,而不是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

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

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

1 个答案:

答案 0 :(得分:5)

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

登录问题很简单,只需使用默认设计登录和after_sign_in_path_for ApplicationController,如上所述

我意识到表单问题的答案就是在这里输入:

我刚为User_Type_1创建了一个普通表单,其中包含User的嵌套属性 并将其发布到UserType1Controller 然后保存了两个对象并从Devise

调用了sign_in_and_redirect助手
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

然后,上面的after_sign_in_path_for方法将它发送到了正确的位置,这一切都很好。