我有两个型号,
class Store < ApplicationRecord
self.primary_key = 'storeid'
has_many : employees
end
class Employee < ApplicationRecord
belongs_to :store, optional: true, foreign_key: :storeid
end
带有以下schema.rb,
create_table "employees", force: :cascade do |t|
t.text "storeid", null: false
t.index ["store_id"], name: "index_employees_on_store_id"
end
create_table "stores", force: :cascade do |t|
t.text "storeid", null: false
t.index ["storeid"], name: "index_stores_on_storeid", unique: true
end
add_foreign_key "employees", "stores", column: "store_id"
add_foreign_key "employees", "stores", column: "storeid", primary_key: "storeid"
end
我的问题是,当我进入Rails控制台并尝试查询Store.first.employees
时,我只是获得了对该模型的引用,然后崩溃了。当我执行Employee.first.stores
时,它将适当的关联商店返回给员工。
ps.s。我知道Rails的命名约定问题
编辑0:这是我的最新迁移
class Keys < ActiveRecord::Migration[6.0]
def up
add_index :stores, [:storeid], :unique => true
add_reference :employees, :stores, foreign_key: true
add_foreign_key :employees, :stores, column: :storeid, primary_key: :"storeid"
end
def down
execute "ALTER TABLE stores DROP CONSTRAINT table_pkey;"
end
end
表迁移:
class Stores < ActiveRecord::Migration[6.0]
def change
create_table :stores do |t|
t.column :storeid, :text, null: false, unique: true
t.column :contactname, :text, null: true
end
end
end
class Employees < ActiveRecord::Migration[6.0]
def change
create_table :employees do |t|
t.column :storeid, :text, null: false, unique: true
t.column :name, :text, null: true
end
end
end
[您的Store
模型似乎缺少外键:
class Store < ApplicationRecord
self.primary_key = 'storeid'
has_many :employees, foreign_key: :storeid
end