我有三个用户角色:
enum role: { staff: 0, clinician: 1, admin: 2 }
我的patient表中有一个user_id列,用于存储创建患者记录的员工用户的ID。为了提高名称的清晰度,我将列从user_id重命名为author_id,并调整了最佳关系,我知道如何引用对外键的更改。
当我尝试访问/ patients / new时,我收到错误:
unknown attribute 'user_id' for Patient.
该错误特别突出了我的新患者方法中的这一行:
@patient = current_user.patients.build
我做错了什么?谢谢你的帮助!
患者表:
create_table "patients", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "age"
t.integer "staff_clinician_id"
t.integer "author_id"
t.index ["author_id"], name: "index_patients_on_author_id"
t.index ["staff_clinician_id"], name: "index_patients_on_staff_clinician_id"
end
患者模型
class Patient < ApplicationRecord
belongs_to :user, -> { where role: :staff }, foreign_key: 'author_id'
员工关注
require 'active_support/concern'
module StaffUser
extend ActiveSupport::Concern
included do
belongs_to :university
has_many :patients
has_many :referral_requests
validates :university_id, presence: true, if: :staff?
end
class_methods do
end
end
这是我的病人控制者:
class PatientsController < ApplicationController
before_action :require_login
def new
@patient = current_user.patients.build
end
def index
authorize Patient
@patients = policy_scope(Patient)
end
def show
@patient = Patient.find(params[:id])
end
def edit
@patient = Patient.find(params[:id])
end
def update
@patients = Patient.all
@patient = Patient.find(params[:id])
if @patient.update_attributes(patient_params)
flash[:success] = "Patient Updated!"
render 'patients/index'
else
render "edit"
end
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, :staff_clinician_id, :author_id, insurance_ids: [], gender_ids: [], concern_ids: [], race_ids: [])
end
end
答案 0 :(得分:1)
似乎你有一个带有has_many :patients
的用户模型(我假设你使用的是StaffUser关注的地方)。 Rails推断关联表上的外键是user_id
。您需要将其更改为:
##user.rb
has_many :patients, foreign_key: "author_id"