我正在使用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表,但实际上recipients是从users表中获取的,换句话说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
欢迎提出任何建议。:)

最佳答案

你必须把你的迁移改成这个。您也可以跳过def drop部分。

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

09-25 20:26