RoR и Postgresql DB: принадлежат принадлежность_ к ассоциации, но не has_many - PullRequest
1 голос
/ 21 апреля 2020

У меня есть две модели,

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

Моя проблема заключается в том, что когда я go на консоль рельсов, и пытаюсь запросить Store.first.employees, я просто получаю ссылку на модель, а затем она падает. Когда я делаю Employee.first.stores, он возвращает соответствующий связанный магазин сотруднику.

ps Я знаю о проблемах, связанных с соглашением об именах 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

1 Ответ

0 голосов
/ 21 апреля 2020

Похоже, в вашей Store модели отсутствует внешний ключ:

class Store < ApplicationRecord
  self.primary_key = 'storeid'
  has_many :employees, foreign_key: :storeid
end
...