2017-09-26 47 views
0

短版,然後在細節之間的多個活動記錄的關係:的Rails:兩款車型

在我的應用程序的用戶有兩個角色,工作人員和臨牀醫生。員工用戶創建病人記錄。有時候,工作人員用戶會爲他們自己的病人創建患者記錄,有時,工作人員用戶會爲另一位工作人員用戶作爲其醫生的患者創建患者記錄。我的意圖是在每個患者記錄中包括創建記錄的工作人員以及作爲該患者醫生的工作人員。我無法找出正確的活動記錄關係來完成這項工作。

在我的患者表中,我有user_id來保存創建患者記錄的職員用戶的ID。在控制檯中,當我創建一個病人並執行Patient.last.user時,它會返回創建該記錄的用戶。

在我的患者表中,我還有doctor_id來保存作爲該患者醫生的工作人員用戶的ID。在當我創建一個病人,做Patient.last.doctor控制檯我得到這個錯誤:

的ActiveRecord :: HasManyThroughAssociationNotFoundError:找不到關聯:用戶在模型病人

我成功地拯救doctor_id,但我似乎無法按照我想要的方式找回醫生的名字。我的東西是不正確的,或者根據我使用的模式,這是不可能的?

詳情:

class User < ApplicationRecord 
    include Clearance::User 
    include StaffUser 
    include ClinicianUser 

    validates :first_name, :last_name, :role, presence: true 

    enum role: { staff: 0, clinician: 1 } 

我有工作人員的關切和生活在應用程序/模型/關注臨牀醫生的關注:

clinician_user.rb

require 'active_support/concern' 

module ClinicianUser 
    extend ActiveSupport::Concern 

    included do 
    has_one :clinician_profile 
    has_many :lists 
    has_many :universities, through: :lists 
    after_create :create_clinician_profile 
    end 

    class_methods do 
    end 
end 

staff_user.rb

module StaffUser 
    extend ActiveSupport::Concern 

    included do 
    belongs_to :university 
    has_many :patients 
    has_many :referral_requests 
    validates :university_id, presence: true 
    end 

    class_methods do 
    end 
end 

這裏是患者模型:

class Patient < ApplicationRecord 
    belongs_to :user, -> { where role: :staff } 

    has_and_belongs_to_many :genders 
    has_and_belongs_to_many :concerns 
    has_and_belongs_to_many :insurances 
    has_and_belongs_to_many :races 
    has_many :referral_requests 
    has_one :doctor, through: :users 
end 

醫生不存在作爲模型 - 它必須爲此工作?有沒有辦法讓它再次引用用戶?

回答

1

您不需要創建單獨的Doctor模型,但您需要更改Patient模型中的活動記錄關聯。既然你說你在病人桌上有doctor_id,那意味着你應該使用belongs_to :doctor而不是has_one :doctor

但通過這樣做,主動記錄會假設你有一張醫生表。自認爲並非如此,您需要class_nameforeign_key參數添加到belongs_to所以活動記錄知道如何正確地產生疑問:

class Patient < ApplicationRecord 
    belongs_to :doctor, class_name: 'User', foreign_key: 'doctor_id' 
end