2017-08-31 9 views
1

私はユーザーモデルと患者モデルを持っています。患者はアプリケーションのユーザーではありません。ユーザーは本質的に患者記録を作成するスタッフです。状況によっては、患者の記録を作成するユーザもその患者の医師である。他の場合には、患者の医師は別個のユーザであってもよい。Rails:そのレコードを作成していないユーザーとレコードを関連付ける

患者の医師のユーザーIDを、患者を作成したユーザーではなく患者モデルに保存します。私が想像している実装では、自分が選択するオプションを含めて、患者の医師を選択するためのフォームのドロップダウンフィールドがあります。これどうやってするの?私はこれについて正しい方法を考えていますか?ここに私の現在の実装である:

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 

患者のスキーマ:スタッフのための1と1:

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 

私は2つの役割を持っています臨床医のために。スタッフのユーザーは患者を作成するユーザーになります。患者記録を作成するスタッフのユーザは、その特定の患者の医師であってもなくてもよい。

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

答えて

1

だけPatientモデルにphysician関係を追加します。

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 

ヒント:あなたのIDが数値であれば、あなたのidのフィールドのintegerを使用しています。

(もちろん、移行によってこれを行う方がいいです、方法がわからない場合はthis postを参照してください)。

はその後paramsphysician_idを許可:最後に

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

関連する問題