2017-08-31 67 views
1

我有一個用戶模型和一個患者模型。患者不是應用程序的用戶。用戶本質上是創建病歷的工作人員。在某些情況下,創建病人記錄的用戶也是該病人的醫生。在其他情況下,患者的醫生可以是單獨的用戶。Rails:將記錄與未創建該記錄的用戶關聯起來

我想將患者醫生的用戶標識保存到患者模型中,而不是恰好創建患者的用戶。我想象的實現是我將在表格中有一個下拉字段供用戶選擇患者的醫師,包括選擇自己的選項。我怎樣才能做到這一點?我甚至想過這是正確的方式?這是我目前的執行:

class Patient < ApplicationRecord 
    belongs_to :user 

class User < ApplicationRecord 
    has_many :patients 

患者控制器

類PatientsController < ApplicationController的

def new 
    @patient = current_user.patients.build 
end 

def create 
    @patient = current_user.patients.build(patient_params) 
    if @patient.save 
     flash[:success] = "Patient Created!" 
     redirect_to new_referral_request_path(patient_id: @patient.id) 
    else 
     Rails.logger.info(@patient.errors.inspect) 
     render 'patients/new' 
end 
end 

private 

def patient_params 
    params.require(:patient).permit(:age, :user_id, insurance_ids: [], gender_ids: [], concern_ids: [], race_ids: []) 

end 
end 

病人的模式:

create_table "patients", force: :cascade do |t| 
    t.datetime "created_at", null: false 
    t.datetime "updated_at", null: false 
    t.integer "age" 
    t.string "user_id" 
    t.index ["user_id"], name: "index_patients_on_user_id" 
    end 

我有兩個作用:一個工作人員和一個爲臨牀醫生。職員用戶將是創建患者的人員。創建患者記錄的工作人員用戶可能是也可能不是該特定患者的醫生。

class User < ApplicationRecord 
    self.inheritance_column = :role 
    enum role: { Staff: 0, Clinician: 1} 

回答

1

只需添加physician關係Patient型號:

class Patient < ApplicationRecord 
    belongs_to :user 
    belongs_to :physician, class_name: 'User' 
end 

然後修改架構:

create_table "patients", force: :cascade do |t| 
    t.datetime "created_at", null: false 
    t.datetime "updated_at", null: false 
    t.integer "age" 
    t.string "user_id" 
    t.integer "physician_id" 
    t.index ["user_id"], name: "index_patients_on_user_id" 
    t.index ["physician_id"], name: "index_patients_on_physician_id" 
end 

提示:使用integerid S場,如果你的ID是數字。

(當然,如果你不知道怎麼做,最好通過遷移來做到這一點,請參閱this post)。

然後允許physician_idparams

def patient_params 
    params.require(:patient).permit(:age, :user_id, :physician_id, insurance_ids: [], gender_ids: [], concern_ids: [], race_ids: []) 
end 

終於在表單中添加下拉列表:

<%= form_for(@patient) do |f| %> 
    <%= f.select :physician_id, User.all.map { |u| [u.name, u.id] } %> 
    ...other fields... 
<% end %> 

現在,您可以同時調用patient.userpatient.physician(可相等)。

+0

嗨Inpego - 我已經通過枚舉實現了職員和臨牀醫師的單個表繼承的角色。問題在於創建病人記錄的工作人員用戶可能是也可能不是該病人的醫生。我如何使用該設置實施您的建議? – mike9182

+0

請用更詳細的描述創建一個新問題並通知我。 – Inpego