【问题标题】:Postgres UndefinedTable: ERROR: relationPostgres UndefinedTable:错误:关系
【发布时间】:2017-06-08 20:11:23
【问题描述】:

我正在使用 postgres 和 rails 来开发应用程序。当我运行rake db:migrate 时出现以下错误:

PG::UndefinedTable: ERROR:  relation "recipients" does not exist
: ALTER TABLE "chat_rooms" ADD CONSTRAINT "fk_rails_564b3640ba"
FOREIGN KEY ("recipient_id")
  REFERENCES "recipients" ("id")

我的迁移文件是:

class AddRecipientToChatRooms < ActiveRecord::Migration[5.0]
  def change
    add_reference :chat_rooms, :recipient, index: true, foreign_key: true
  end

  def drop
    remove_reference :chat_rooms, :recipient, index: true, foreign_key: true
  end
end

我的架构是:

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

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

  create_table "chat_rooms", force: :cascade do |t|
    t.string   "title"
    t.integer  "sender_id"
    t.datetime "created_at",   null: false
    t.datetime "updated_at",   null: false
    t.integer  "recipient_id"
    t.integer  "created_id"
    t.index ["created_id"], name: "index_chat_rooms_on_created_id", using: :btree
    t.index ["recipient_id"], name: "index_chat_rooms_on_recipient_id", using: :btree
    t.index ["sender_id"], name: "index_chat_rooms_on_sender_id", using: :btree
    t.index ["title"], name: "index_chat_rooms_on_title", unique: true, using: :btree
  end

  create_table "messages", force: :cascade do |t|
    t.text     "body"
    t.integer  "user_id"
    t.integer  "chat_room_id"
    t.datetime "created_at",   null: false
    t.datetime "updated_at",   null: false
    t.index ["chat_room_id"], name: "index_messages_on_chat_room_id", using: :btree
    t.index ["user_id"], name: "index_messages_on_user_id", using: :btree
  end

  create_table "users", force: :cascade do |t|
    t.string   "name"
    t.string   "email"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["email"], name: "index_users_on_email", unique: true, using: :btree
    t.index ["name"], name: "index_users_on_name", unique: true, using: :btree
  end

end

我已阅读有关此问题的信息,并且我了解 postgresql 正在寻找 recipients 表,但实际上收件人是从 users 表中获取的,换句话说,收件人是用户的别名。我已经在我的模型中指定了:

belongs_to :recipient, foreign_key: :recipient_id, class_name: 'User'

我对如何解决问题有一些想法,但不确定它是否会保持参考完整性

  • 创建一个名为recipients_id 的整数字段,然后添加一个外键:add_foreign_key :chat_rooms, :users, column: :recipients_id, primary_key: :user_id

欢迎提出任何建议。 :)

【问题讨论】:

    标签: ruby-on-rails postgresql migration


    【解决方案1】:

    您必须将迁移更改为此。您也可以跳过def drop 部分。

    def change 
      add_column :chat_rooms, :recipient_id, :integer, index: true
      add_foreign_key :chat_rooms, :users, column: :recipient_id
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-18
      • 2015-07-29
      • 1970-01-01
      • 2020-05-08
      • 2021-03-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多