我正在使用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正在寻找收件人表,但实际上收件人来自用户表,换言之,收件人是用户的别名。我在我的模型中指定了:
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
欢迎任何建议。 :)
答案 0 :(得分:0)
您必须将迁移更改为此。您也可以跳过def drop
部分。
def change
add_column :chat_rooms, :recipient_id, :integer, index: true
add_foreign_key :chat_rooms, :users, column: :recipient_id
end