Rails 5 ассоциация с другим внешним ключом - PullRequest
0 голосов
/ 28 августа 2018

Я думаю, что что-то упустил при создании ассоциации с foreign_key в Rails.

У меня есть 2 модели: Company и Employee. Компания has_many сотрудников и Сотрудник belongs_to компании. У Company есть атрибут company_code, и я смогу выяснить, в какой компании работает сотрудник, используя company_code вместо company_id.

Сначала я создал модели:

rails g model Company company_code:integer:index name

rails g model Employee joined:date:index salary:integer

Затем я сгенерировал миграцию для добавления столбца company_code в таблицу employees.

class AddReferenceToEmployee < ActiveRecord::Migration[5.1]
  def change
    add_column :employees, :company_code, :integer, index: true
    add_foreign_key :employees, :companies, column: :company_code
  end
end

И, наконец, я добавил внешний ключ на уровне модели.

class Company < ApplicationRecord
  has_many :employees, foreign_key: :company_code
end

class Employee < ApplicationRecord
  belongs_to :company, foreign_key: :company_code
end

Однако я все еще не могу создать правильную ассоциацию.

company = Company.create(name: 'test', company_code: 123)
company.employees.create(joined: Date.today, salary: 1000)

Создает запись сотрудника с company_code = 1 вместо 123.

Когда я пытаюсь создать новый экземпляр сотрудника

company.employees.new

будет генерироваться

#<Employee id: nil, joined: nil, salary: nil, created_at: nil, updated_at: nil, company_code: 1>

Чего мне не хватает? Это правильный способ сделать это?

Сильфон мой schema.rb

ActiveRecord::Schema.define(version: 20180828052633) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "companies", force: :cascade do |t|
    t.integer "company_code"
    t.string "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["company_code"], name: "index_company_on_company_code"
  end

  create_table "employees", force: :cascade do |t|
    t.date "joined"
    t.integer "salary"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer "company_code"
  end

  add_foreign_key "employees", "companies", column: "company_code"
end

1 Ответ

0 голосов
/ 02 сентября 2018
class Company < ApplicationRecord
  has_many :employees, primary_key: :company_code, foreign_key: :company_code
end

class Employee < ApplicationRecord
  belongs_to :company, foreign_key: :company_code, primary_key: :company_code
end
...