【问题标题】:Rails polymorphic user model with Devise使用 Devise 的 Rails 多态用户模型
【发布时间】:2012-03-05 04:34:26
【问题描述】:

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

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

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 的用户)

我知道我可以使用AppicationController 中的after_sign_in_path_for(resource) 覆盖以某种方式在登录时重定向到站点的右侧部分。类似:

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 之后登录?

另外,如果我走错了路,那么正确的方法是什么?

【问题讨论】:

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


    【解决方案1】:

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

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

    在这里输入表单问题时,我意识到了答案:

    我刚刚为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方法将它发送到正确的位置,一切都很好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-15
      • 2013-11-08
      • 2016-12-10
      • 1970-01-01
      相关资源
      最近更新 更多