[英]Rails polymorphic user model with 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
我這樣做的原因,而不是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
類型的User_Type_1
,然后在sign_up之后簽名?
另外,如果我以錯誤的方式解決這個問題,那么正確的方法是什么?
我能夠回答我自己的問題並將其放在這里,以便它可以幫助其他人解決同樣的問題。
登錄問題很簡單,只需使用默認設計登錄和ApplicationController
的after_sign_in_path_for
,如上所述
我在這里輸入了表格問題的答案:
我剛為User_Type_1
創建了一個普通表單,其中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
方法將它發送到正確的位置,這一切都很好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.