设计:使用单表继承实例化current_user



我正在使用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

您需要覆盖应用程序控制器中的登录路径方法,希望对您有所帮助。

您需要在

模型内添加get_some_attribute方法User

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中有一些共享逻辑,因为它将在用户模型中调用get_some_attribute,如果您不需要它,您可以将其删除。

祝你好运!

最新更新