【问题标题】:Rails possible problem with has_many polymorphic associationRails 可能存在 has_many 多态关联的问题
【发布时间】:2018-12-14 14:27:53
【问题描述】:

在我的应用程序中,我有以下模型:

用户

心理学家有_许多教室

教师有_many 个教室

父母有_许多孩子

导演所属学校

协调员属于学校

我的用户模型如下所示:

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_atupdated_at 之外没有任何其他列。

是否可以只创建这些具有关系的模型而让它们的表没有数据?

【问题讨论】:

    标签: ruby-on-rails polymorphic-associations


    【解决方案1】:

    也许您打算使用单表继承而不是多态关系。如果PsychologistUser,应该是这样。

    然后你需要在 users 表中添加一个 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
    

    type 列将填充实际类的名称,例如 "Teacher" 等。

    由于Teacher 的实例也是User 的实例,它将具有teacher.has_role?('foo')teacher.roles,您将能够创建类似Role.create(user: teacher, name: 'bar') 的角色。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多