Rails 数据库模式:共享记录



我有病人的用户。但我想增加用户相互共享患者的能力。目前,我正在 SharedPatient 表上创建user_id指示患者已与哪个用户共享,patient_id指示患者。这有效,但我必须获取User.patients,然后在SharedPatient表中查询他们有权访问的其他患者的ID,然后在Patient表中查询他们的患者记录。

我真的只是希望能够调用User.patients并检索他们共享的患者和他们自己创建的患者。指示用户是否是创建者的布尔值似乎是在它们之间进行排序的可靠方法,但我担心它有点黑客。是否有解决此问题的首选方法或我忽略的活动记录关系?

编辑

class User < ActiveRecord::Base
  has_many :patients
  has_many :notes
  has_many :shared_patients
end
class SharedPatient < ActiveRecord::Base
  belongs_to :user
  belongs_to :patient
end
class Patient < ActiveRecord::Base
  belongs_to :user
  has_many :recordings, dependent: :destroy
  has_many :notes, dependent: :destroy
  has_many :shared_patients, dependent: :destroy 
end

对于您问题的第一部分

患者.rb

class Patient < ActiveRecord::Base
:has_and_belongs_to_many :users, :through => :sharedpatients
...
end

用户.rb

class User < ActiveRecord::Base
:has_and_belongs_to_many :patients, :through => :sharedpatients
...
end

共享患者.rb

class SharedPatient < ActiveRecord::Base
:belongs_to :user
:belongs_to :patient
...
end

因此,例如,您将拥有:

@user=User.find(params[:id])
@patient=@user.patients.first
@users=@patient.users

等等,你明白了。

对于第二部分,您应该在患者表中添加一个额外的user_id字段,例如creator_id,该字段将保存创建患者的用户的 ID。然后在你的用户.rb:

has_many :created_patients, :class_name =>  "Patient", :foreign_key => 'creator_id'

在您的患者.rb中:

belongs_to :creator, :class_name =>  "User", :foreign_key => 'creator_id'

然后,您将拥有以下方法:

user.created_patients #list of his own patients
patient.creator # who is the doctor who created him

我建议在它们之间添加一个关系模型(可以命名为联系人,或者其他名称,我将在下面使用联系人)。然后在该模型上添加一个标志,指示用户是该患者的主要(或创建者或您想要的任何术语)。然后,您可以添加关联以将它们全部绑定在一起:

class User < ActiveRecord::Base
  has_many :contacts, dependent: :destroy
  has_many :patients, through: :contacts
end
class Patient < ActiveRecord::Base
  has_many :contacts, dependent: :destroy
  has_many :users, through: :contacts
end
class Contact < ActiveRecord::Base
  belongs_to :user
  belongs_to :patient
  # has a boolean attribute named primary
  scope :primary, -> { where(primary: true) }
end

最新更新