class Participant < ApplicationRecord after_create :create_onboarding_items_for_forms # Associations belongs_to :employer, optional: false has_many :employments has_many :workers, through: :employments has_many :service_contracts has_many :vendors, through: :service_contracts has_many :employer_records has_many :employers, through: :employer_records has_and_belongs_to_many :programs has_many :bank_accounts, as: :owner has_many :onboarding_items, as: :owner accepts_nested_attributes_for :onboarding_items # Validations validates :first_name, :last_name, :ssn, presence: true validates :ssn, uniqueness: { message: "SSN is already taken by another participant" }, unless: :ssn_already_taken_by_employer? validates :employer_id, presence: true def full_name "#{first_name} #{last_name}" end private def ssn_already_taken_by_employer? # Check if the SSN already exists in the Employer model, excluding the current participant's employer Employer.where.not(id: employer_id).exists?(ssn: ssn) end def create_onboarding_items_for_forms # Ensure there's a 'Role' model with an association set up between Forms and Roles. participant_role = Role.find_by(name: 'Participant') return unless participant_role # Fetch all forms associated with the 'Participant' role. forms = Form.joins(:roles).where(roles: { id: participant_role.id }) forms.each do |form| self.onboarding_items.find_or_create_by(form: form) end end end