简体   繁体   English

has_many多态关联的Rails可能出现的问题

[英]Rails possible problem with has_many polymorphic association

In my application, I have the following models: 在我的应用程序中,我具有以下模型:

User 用户

Psychologist has_many classrooms 心理学家has_many许多教室

Teacher has_many classrooms 老师有很多教室

Parent has_many children 父母有很多孩子

Director belongs_to school 主任属于学校

Coordinator belongs_to school 协调员属于学校

My user model looks like the following: 我的用户模型如下所示:

class User < ActiveRecord
   has_many :roles

   def has_role? role_name
     self.roles.where(role_type: role_name).any?
   end
end

The Role model is polymorphic: 角色模型是多态的:

class Role < ApplicationRecord
  belongs_to :user
  belongs_to :roleable, polymorphic: true
end

And the other models are rollable. 其他型号是可卷曲的。

My question is the following, it seems that this is not correct, because some models like: Director, Psychologists, Teachers, Coordinator and Parent. 我的问题是以下内容,看来这是不正确的,因为某些模型如下:主任,心理学家,教师,协调员和父母。 They only have relationships and their database tables do not have any other column except created_at , updated_at . 它们仅具有关系,并且其数据库表除created_atupdated_at外没有任何其他列。

Is it okay to only create these models with relationships and have their tables without data? 可以只创建具有关系的模型并使其表中没有数据吗?

Maybe you intend to use single table inheritance and not polymorphic relationships . 也许您打算使用单表继承而不是多态关系 If a Psychologist is a User , it should be the case. 如果PsychologistUser ,那就应该如此。

Then you need to add a type column of type VARCHAR to the users table, and set up your models like: 然后,您需要向用户表中添加VARCHAR type列,并按如下所示设置模型:

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

The type column will be populated with the name of the actual class, like "Teacher" etc. type列将填充实际班级的名称,例如"Teacher"等。

As an instance of Teacher is also an instance of User , it will have teacher.has_role?('foo') and teacher.roles , and you will be able to create a role like Role.create(user: teacher, name: 'bar') . 由于Teacher的实例也是User的实例,它将具有teacher.has_role?('foo')teacher.roles ,您将能够创建Role.create(user: teacher, name: 'bar')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM