class Employer < ApplicationRecord # Direct association with participants has_many :direct_participants, class_name: 'Participant' # Association through EmployerRecord has_many :employer_records has_many :indirect_participants, through: :employer_records, source: :participant # Association with Workers through direct_participants has_many :workers, through: :direct_participants # Other methods... def full_name "#{first_name} #{last_name}" end has_many :onboarding_items, as: :owner accepts_nested_attributes_for :onboarding_items class Employer < ApplicationRecord # Associations and other methods as before... validate :unique_as_participant, if: -> { ssn_changed? || new_record? } validates :ssn, uniqueness: { allow_blank: true }, if: -> { ssn.present? } validates :tin, uniqueness: { allow_blank: true }, if: -> { tin.present? } private def unique_as_participant if Participant.exists?(ssn: ssn) && (id.blank? || Participant.where.not(id: id).exists?(ssn: ssn)) errors.add(:ssn, 'A participant with the same SSN already exists') end end end def create_onboarding_items_for_forms # Ensure there's a 'Role' model with an association set up between Forms and Roles. employer_role = Role.find_by(name: 'Employer') return unless employer_role # Fetch all forms associated with the 'Employer' role. forms = Form.joins(:roles).where(roles: { id: employer_role.id }) forms.each do |form| self.onboarding_items.find_or_create_by(form: form) end end end