我正在尝试为我的用户创建不同的配置文件类型。
我有一个用户模型。
User
类型有一个与Profile
相关的,所以它是has_one :profile
,但Page
类型有一种与Page
相关的,因此它是has_one :page
但是,我对两者使用相同的User
表,并且我正在设置帐户类型。
我想知道,如何根据我的用户帐户类型来确定这种关系
编辑
用户模型has_one:profile profile belongs_to:User Page belongs_to:User帐户类型为";用户";(进入Profile模型),或";页面";(属于Page模型)。
class User < ActiveRecord::Base
has_one :profile, :class_name => 'Here it should be either PROFILE or PAGE'
end
class Profile < ActiveRecord::Base
belongs_to :user
end
class Page < ActiveRecord::Base
belongs_to :user
end
我一直在阅读API,发现:class_name,现在我的挑战是动态地确定它
编辑
编辑了一点页面模型和用户模型。
也许proc
有效?
class User < ActiveRecord::Base
TYPES = { 'user' => 'Profile', 'page' => 'Page' }
has_one :profile, :class_name => proc { TYPES[self.type].constantize }
end
如果有效,请考虑添加一个表来存储用户类型:
class User < ActiveRecord::Base
TYPES = { 'user' => 'Profile', 'page' => 'Page' }
has_one :profile, :class_name => proc { TYPES[self.type].constantize }
belongs_to :user_type
end
class UserType < ActiveRecord::Base
has_many :users
end