RoR和Postgresql DB:belongs_to关联有效,但has_many不起作用

问题描述 投票:0回答:1

我有两个型号,

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

ruby-on-rails postgresql webpack-dev-server
1个回答
0
投票

[您的Store模型似乎缺少外键:

class Store < ApplicationRecord
  self.primary_key = 'storeid'
  has_many :employees, foreign_key: :storeid
end
© www.soinside.com 2019 - 2024. All rights reserved.