![](/img/trans.png)
[英]Multiple Table Inheritance in Rails 4/Devise setting the current_user
[英]devise: instance the current_user using single table inheritance
我正在使用Rails 3.0.9並設計用於身份驗證。 現在,由於我需要使用多態性,因此我嘗試使用單表繼承,所以我有兩個類:UserType1和UserType2,它們從User類繼承。 我需要該Devise實例正確地取決於用戶類型的current_user。
例如,
class User < ActiveRecord::Base
#devise and other user logic
end
class UserType1 < User
def get_some_attribute
return "Hello, my type is UserType1"
end
end
class UserType2 < User
def get_some_attribute
return "Hello, my type is UserType2"
end
end
In controller
class MyController < ApplicationController
def action
@message = current_user.get_some_attribute #depending the type using polymorphism
render :my_view
end
end
正是您所需要的: http : //blog.jeffsaracco.com/ruby-on-rails-polymorphic-user-model-with-devise-authentication
您需要在應用程序控制器中覆蓋登錄路徑方法,希望對您有所幫助。
您將需要在User
模型內添加get_some_attribute
方法
Module User < ActiveRecord::Base
#devise and other user logic
def get_some_attribute
#You can put shared logic between the two users type here
end
end
然后,在用戶子類型中覆蓋它,如下所示:
Module UserType1 < User
def get_some_attribute
super
return "Hello, my type is UserType1"
end
end
Module UserType2 < User
def get_some_attribute
super
return "Hello, my type is UserType2"
end
end
然后, current_user.get_some_attribute
將按預期工作,如果您想閱讀有關Ruby中的重寫方法的更多信息,可以在這里閱讀。
我添加了super
因為我假設您在get_some_attribute
具有一些共享邏輯,因為它將在User模型中調用get_some_attribute
,如果不需要它可以將其刪除。
祝好運!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.