2014-02-26 67 views
0

我有拥有病人的用户。但我想增加用户分享病人的能力。此刻,我在SharedPatient表中创建了user_id,指示病人已与哪个用户共享,patient_id指示病人。这有效,但我必须获取User.patients,然后在SharedPatient表中查询他们有权访问的其他患者的ID,然后在患者表中查询患者记录。Rails数据库架构:共享记录

我真的只是想调用User.patients并检索他们共享的患者和他们自己创建的患者。指示用户是否是创建者的布尔值似乎是在它们之间进行排序的一种可靠方式,但我担心这有点冒失。有没有一种首选的方法来解决这个问题或我忽略的ActiveRecord关系?

编辑

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 
+1

请分享模型的细节。 –

+0

你可以查看我的答案的底部如何获得created_by thingy ... –

回答

1

对于你的问题

patient.rb

class Patient < ActiveRecord::Base 

:has_and_belongs_to_many :users, :through => :sharedpatients 
... 
end 

user.rb

class User < ActiveRecord::Base 

:has_and_belongs_to_many :patients, :through => :sharedpatients 
... 
end 

sharedpatient的第一部分.rb

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

end 

因此,举例来说,你将有:

@user=User.find(params[:id]) 
@[email protected] 
@[email protected] 

等等,你得到的图片。

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

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

,并在您patient.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 
1

我建议增加一个关系模型之间(可能被命名联系人,或不同的东西,我将使用以下联系方式)。然后在该模型上添加一个标志,指示用户是该患者的主要(或创建者或任何您想要的术语)。然后,你可以添加协会,以配合他们一起:

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 
+0

这就是我在第二段中的想法(显然我没有很好地描述),但我担心我错过了一个更清洁的方式某种程度上。 – Morgan

+0

我向Contact类添加了一个范围,可以派上用场。 – Coenwulf