【问题标题】:Rails : Associating a record with a user who did not create that recordRails :将记录与未创建该记录的用户相关联
【发布时间】:2017-08-31 19:40:02
【问题描述】:

我有一个用户模型和一个患者模型。患者不是该应用程序的用户。用户本质上是创建患者记录的工作人员。在某些情况下,创建患者记录的用户也是该患者的医生。在其他情况下,患者的医生可能是单独的用户。

我想将患者医生的用户 ID 保存到患者模型,而不是碰巧创建患者的用户。我想象的实现是,我将在表单中有一个下拉字段供用户选择患者的医生,包括选择自己的选项。我怎样才能做到这一点?我什至以正确的方式思考这个问题吗?这是我当前的实现:

class Patient < ApplicationRecord
    belongs_to :user

class User < ApplicationRecord
    has_many :patients

病人控制者

类患者控制器

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}

【问题讨论】:

    标签: ruby-on-rails


    【解决方案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
    

    提示:如果您的 id 是数字,请在您的 ids 字段中使用 integer

    (当然,最好通过迁移来做到这一点,如果你不知道怎么做,请参阅this post)。

    然后在params 中允许physician_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(可以相等)。

    【讨论】:

    • 嗨 Inpego - 我已经通过枚举实现了工作人员和临床医生的单表继承角色。问题是创建患者记录的员工用户可能是也可能不是该患者的医生。我如何通过该设置实施您的建议?
    • 请创建一个具有更详细描述的新问题并通知我。
    猜你喜欢
    • 1970-01-01
    • 2016-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多