Reputation: 289
I have three user roles:
enum role: { staff: 0, clinician: 1, admin: 2 }
I had a user_id column in my patients table to store the id of the staff user who created the patient record. To improve the clarity of the name, I renamed the column from user_id to author_id and adjusted the relationship best I knew how to reference the change to the foreign key.
When I try to access /patients/new, I get the error:
unknown attribute 'user_id' for Patient.
The error specifically highlights this line in my new patients method:
@patient = current_user.patients.build
What am I doing incorrectly? Thanks for any help!
patients table:
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
Patient Model
class Patient < ApplicationRecord
belongs_to :user, -> { where role: :staff }, foreign_key: 'author_id'
Staff User concern
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
Here is my patients controller:
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
Upvotes: 0
Views: 763
Reputation: 3308
Seems you have a User model with has_many :patients
(I assume that's where you used your StaffUser concern). Rails infers that the foreign key on the association table is user_id
. You need to change this to:
##user.rb
has_many :patients, foreign_key: "author_id"
Upvotes: 2