Xg Divine
Xg Divine

Reputation: 1

How to associate table column with another table

So basically I like to know what association i need to link my routes table with employees table. I have a routes table with an employees column (array type) which holds employee id's. I also have an employee table that has (first_name, last_name, phone_number).

A has_many :employees, foreign_key: :employees, class_name: :Employee does not work and gives an error. Any ideas?

This error is given

ActiveRecord::StatementInvalid (PG::UndefinedColumn: ERROR:  column employees.employees does not exist)
LINE 1: SELECT "employees".* FROM "employees" WHERE "employees"."emp...

Upvotes: 0

Views: 824

Answers (1)

max
max

Reputation: 102368

Using an array column here is a just bad idea:

  • Violates first normal form.
  • Doesn't let you use foreign keys to maintain referential integrity.
  • Doesn't work with ActiveRecord assocations that expect you to model your data in a sane way.
  • You will need to write queries by hand.

Instead you most likely want is a self-referential assocation:

class AddManagerToEmployees < ActiveRecord::Migration[6.1]
  def change
    add_reference :employees, :manager, 
       null: true, 
       foreign_key: { to_table: :employees }
  end
end

class Employee < ApplicationRecord
  belongs_to :manager, 
    class_name: 'Employee'
  has_many   :subordinates, 
    class_name: 'Employee',
    foreign_key: :manager_id
end

If the manager-employee relation should be many to many instead of one to many use a join table.

Upvotes: 0

Related Questions