2

I have a Company that has many Users through a join table company_user. Each user should work for only one Company. This is a 1 to many relationship.

I have looked around for this and found the solution in https://stackoverflow.com/a/7080017/883102

But I get the error

PG::UndefinedTable: ERROR: relation "companies" does not exist LINE 5: WHERE a.attrelid = '"companies"'::regclass

When I try to create a Company. How can I solve this?

My models are

Company

class Company < ActiveRecord::Base
  has_many :employments
  has_many :users, :through => :employments
end

Users

class User < ActiveRecord::Base
  ...
end

Employment

class Employment < ActiveRecord::Base
  belongs_to :company
  belongs_to :user
end

The migration for my join table is

create_table :employment do |t|
    t.belongs_to :company
    t.belongs_to :user
    t.timestamps
end

My schema.rb

create_table "company", force: true do |t|
  t.integer  "rating"
  t.integer  "phone"
  t.string   "name"
  t.string   "address"
  t.string   "email"
  t.datetime "created_at"
  t.datetime "updated_at"
end

create_table "employment", id: false, force: true do |t|
  t.integer  "company_id"
  t.integer  "user_id"
  t.datetime "created_at"
  t.datetime "updated_at"
end

create_table "users", force: true do |t|
  t.string   "name"
  t.string   "email"
  t.datetime "created_at"
  t.datetime "updated_at"
  t.string   "password_digest"
  t.string   "remember_token"
  t.string   "role"
end
Community
  • 1
  • 1
Jeff Finn
  • 1,975
  • 6
  • 23
  • 52

1 Answers1

4

Hi I found the answer here https://stackoverflow.com/a/24318236/883102

The problem was that my table names were in the singular form, I changed these in the migration and then re-created the database. It all seems to be working fine now.

My User class ended up as

class User < ActiveRecord::Base
  has_one :employment
  has_one :company, :through => :employment
end

This was to allow bi-directional associations

Community
  • 1
  • 1
Jeff Finn
  • 1,975
  • 6
  • 23
  • 52