Rails 5与不同外键的关联

时间:2018-08-28 02:50:12

标签: ruby-on-rails activerecord ruby-on-rails-5 associations rails-activerecord

我认为在Rails中创建与Foreign_key的关联时,我错过了一些东西。

我有2个模型:CompanyEmployee。公司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 :(得分:1)

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