Rails Active Record Associations 的问题

joezhang · December 16, 2016 · Last by flemon1986 replied at December 23, 2016 · 1897 hits

class Physician < ApplicationRecord
  has_many :appointments
  has_many :patients, through: :appointments
end

class Appointment < ApplicationRecord
  belongs_to :physician
  belongs_to :patient
end

class Patient < ApplicationRecord
  has_many :appointments
  has_many :physicians, through: :appointments
end

关系如上,医生,病人,预约,很好理解,不过如果想设计 Physician 和 Patient 同属于一个表 User,应该怎么写呢?难道要用 Polymorphic Associations?感觉这样设计有点别扭。请指教。谢谢!

class User < ApplicationRecord
  belongs_to :role, polymorphic: true
end

class Physician < ApplicationRecord
  has_many :users, as: :role
end

class Patient < ApplicationRecord
  has_many :users, as: :role
end

继承类是你想要的效果么?

# users schema
# type String
class Physician < User
end

继承自 User 数据表都存在 users 上,会通过 type 字段分别子类

谢谢 yingce 不知道是统一在一个 User 表还是直接分成 Physician 和 Patient 两个表好,纠结中。

#2 楼 @joezhang 我觉得是看业务吧 如果只是一个身份标示的话在一张表就行 如果涉及到登陆 后台管理关联也不同的话就可以分开两张

多态关联好像是有三张表啊,不符合楼主自己提的需求。继承好像也有个问题,就是一个 user 同属于医生和病人不能处理。

@pinewong 综合考虑,最后还是选择三表多态关联,医生和病人属于不同的表。😀

分开是好的,看是很相似的两个或几个模型,不同的表现一旦多了,一表多态继承就很麻烦了 初始最多就两个不同名称的表的结构一样,看似多余,但是无害,方便分别扩展

You need to Sign in before reply, if you don't have an account, please Sign up first.