obdev/app/controllers/participants_controller.rb

127 lines
3.3 KiB
Ruby

class ParticipantsController < ApplicationController
before_action :set_participant, only: [:show, :edit, :update, :destroy]
def index
@participants = Participant.order(:last_name).page(params[:page]).per(5) # Adjust the number per page as needed
end
def show
@participant = Participant.includes(:employments).find(params[:id])
@workers = @participant.workers # Fetch associated workers
@employment = Employment.new # Initialize a new Employment object
@participant = Participant.includes(employments: :worker).find(params[:id])
@employments = @participant.employments.includes(:worker).order('workers.last_name')
end
def new
@participant = Participant.new
end
def create
@participant = Participant.new(participant_params)
Participant.transaction do
if params[:is_employer] == 'yes'
employer = Employer.new(employer_params_from_participant(@participant))
if employer.save
@participant.employer = employer
else
Rails.logger.debug "Employer creation failed: #{employer.errors.full_messages}"
raise ActiveRecord::Rollback, "Employer could not be saved"
end
end
if @participant.save
redirect_to @participant, notice: 'Participant was successfully created.'
else
raise ActiveRecord::Rollback, "Participant could not be saved"
end
end
rescue ActiveRecord::RecordInvalid => e
Rails.logger.error("Participant creation failed: #{e.message}")
flash.now[:alert] = "Error: #{e.message}"
render :new
end
def edit
end
def update
if @participant.update(participant_params)
redirect_to @participant, notice: 'Participant was successfully updated.'
else
render :edit
end
end
def destroy
@participant.destroy
redirect_to participants_url, notice: 'Participant was successfully destroyed.'
end
def link_worker
@participant = Participant.find(params[:id])
@employment = @participant.employments.new(employment_params)
if @employment.save
redirect_to @participant, notice: 'Worker was successfully linked.'
else
Rails.logger.debug @employment.errors.full_messages
flash[:alert] = @employment.errors.full_messages.to_sentence
render 'show'
end
end
private
def set_participant
@participant = Participant.find(params[:id])
end
def participant_params
params.require(:participant).permit(
:first_name,
:last_name,
:address_line_1,
:address_line_2,
:city,
:state,
:zip,
:phone,
:email,
:mci,
:dob,
:ssn,
:gender,
:employer_id
)
end
def employer_params_from_participant(participant)
{
first_name: participant.first_name,
last_name: participant.last_name,
address_line_1: participant.address_line_1,
address_line_2: participant.address_line_2,
city: participant.city,
state: participant.state,
zip: participant.zip,
phone: participant.phone,
email: participant.email,
dob: participant.dob,
ssn: participant.ssn,
gender: participant.gender
}
end
def employment_params
params.require(:employment).permit(:worker_id, :start_date, :end_date)
end
end