'Single Table Inheritance + Relationships

I'm creating a rails 5 application (a sort of job finder that connects recruiters with applicants).

Here is a part of my model configuration:

class User < ActiveRecord::Base
  has_and_belongs_to_many :tag
end

class Applicant < User
  has_many :experience
  has_many :match
end

class Recruiter < User
  has_one :company
  has_many :offer
end

class Experience < ActiveRecord::Base
  belongs_to :applicant, :foreign_key => "user_id"
  has_one :company
end

And these are extracts from my schema file:

create_table "users", force: :cascade do |t|
    t.string "type", null: false
    t.string "login", limit: 40, null: false
    t.string "password", limit: 500, null: false
    t.bigint "company_id"

    t.index ["company_id"], name: "index_users_on_company_id"
    t.index ["login"], name: "index_users_on_login", unique: true
  end

create_table "experiences", force: :cascade do |t|
    t.string "job_name", limit: 100, null: false
    t.bigint "company_id"
    t.bigint "user_id", null: false
    t.text "description"
    t.index ["company_id"], name: "index_experiences_on_company_id"
    t.index ["job_name"], name: "index_experiences_on_job_name"
    t.index ["user_id"], name: "index_experiences_on_user_id"
  end

add_foreign_key "users", "companies"
add_foreign_key "experiences", "companies"
add_foreign_key "experiences", "users"

An Experience is attached to the model Applicant through the table user (which contain a type field for the STI), this is why I specified "foreign_key => 'user_id'" in Experience model.

My problem is when I try to access at the first experience of an applicant, I get this error:

PG::UndefinedColumn: ERROR: column experiences.applicant_id does not exist LINE 1: SELECT "experiences".* FROM "experiences" WHERE "experiences...

I hope you can help me. Thanks!



Solution 1:[1]

As stated in the docs:

By convention, Rails assumes that the column used to hold the foreign key on the other model is the name of this model with the suffix _id added.

Try doing:

class Applicant < User
  has_many :experiences, foreign_key: :user_id
  has_many :matches
end

Note that it is conventional to use the plural with the has_many association.

BTW, it's no obvious to me why you're using STI, but I'm sure there are good reasons.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jvillian