I have two models: one for patient and one for referral request. I've created two forms - one that allows a user to create a new patient and another that allows a user to create a referral request. A patient can have many referral requests, and and a referral request will belong to the user who created it as well as the patient it is created for.
I am having trouble figuring out how to link these forms together in a way that creates the association between the patient and the referral request being created for them by the user. I think I have to put something in the new or create actions of the referral requests controller, but I can't get anything I've tried to work.
Any help appreciated for a rookie!
Patients Controller:
class 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 '/referral_requests/new'
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
Referal Requests Controller:
class ReferralRequestsController < ApplicationController
before_action :logged_in_user, only: [:show, :index, :new, :create, :edit, :update, :destroy]
def index
if logged_in?
@referral_request = current_user.referral_requests.build
@feed_items = current_user.feed.paginate(page: params[:page])
else
@feed_items =[]
end
end
def create
@referral_request = current_user.referral_requests.build(referral_request_params)
if @referral_request.save
flash[:success] = "Referral Request Created!"
render 'referral_requests/index'
else
Rails.logger.info(@referral_request.errors.inspect)
@feed_items = []
render 'static_pages/home'
end
end
def destroy
end
def new
@referral_request = current_user.referral_requests.build if logged_in?
end
private
def referral_request_params
params.require(:referral_request).permit(:content, concern_ids: [],
insurance_ids: [], race_ids: [], language_ids: [], gender_ids: [])
end
end
you need to pass in the patient_id in your redirect in the create action of PatientsController.
redirect_to '/referral_requests/new'
should become
redirect_to new_referral_request_path(patient_id: @patient.id)
then in ReferralRequestsController you can associate the newly built referral_request with the patient
def new
@patient = Patient.find(params[:patient_id])
@referral_request = current_user.referral_requests.build(patient: @patient) if logged_in?
end
Then in your referral_requests/new.html.erb form you can add a hidden_field_tag
form_for(@referral_request) do |f|
f.hidden_field :patient_id
.....
end
which will then add patient_id to into the form params and pickup the patient_id that got associated in the new action of the controller
You will need to add :patient_id into your referral_request_params method as well