Rails:将记录与未创建该记录的用户关联起来
问题描述:
我有一个用户模型和一个患者模型。患者不是应用程序的用户。用户本质上是创建病历的工作人员。在某些情况下,创建病人记录的用户也是该病人的医生。在其他情况下,患者的医生可以是单独的用户。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}
答
只需添加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
提示:使用integer
您id
S场,如果你的ID是数字。
(当然,如果你不知道怎么做,最好通过迁移来做到这一点,请参阅this post)。
然后允许physician_id
在params
:
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.user
和patient.physician
(可相等)。
嗨Inpego - 我已经通过枚举实现了职员和临床医师的单个表继承的角色。问题在于创建病人记录的工作人员用户可能是也可能不是该病人的医生。我如何使用该设置实施您的建议? – mike9182
请用更详细的描述创建一个新问题并通知我。 – Inpego