在我的应用程序中,我有以下模型:
用户
心理学家has_many教室
教师has_many教室
父母has_many子女
主任belongs_to学校
协调员belongs_to学校
我的用户模型如下所示:
class User < ActiveRecord
has_many :roles
def has_role? role_name
self.roles.where(role_type: role_name).any?
end
end
角色模型是多态的:
class Role < ApplicationRecord
belongs_to :user
belongs_to :roleable, polymorphic: true
end
其他型号是可滚动的。
我的问题如下,这似乎是不正确的,因为有些模型,如:主任,心理学家,教师,协调员和家长。它们只有关系,它们的数据库表除了created_at、updated_at之外没有任何其他列。
只使用关系创建这些模型并使其表没有数据可以吗?
发布于 2018-12-14 14:35:05
也许您打算使用单表继承而不是多态关系。如果Psychologist
是User
,则应该是这样。
然后,您需要向users表中添加一个VARCHAR
类型的VARCHAR
列,并设置如下模型:
class User < ApplicationRecord
has_many :roles
def has_role? role_name
self.roles.where(role_type: role_name).any?
end
end
class Psychologist < User
# no need to set up roles
end
class Teacher < User
# no need to set up roles
end
class Role < ApplicationRecord
belongs_to :user
# no polymorphic
end
type
列将使用实际类的名称填充,如"Teacher"
等。
由于Teacher
的一个实例也是User
的一个实例,它将具有teacher.has_role?('foo')
和teacher.roles
,您将能够创建类似于Role.create(user: teacher, name: 'bar')
的角色。
https://stackoverflow.com/questions/53781595
复制相似问题