如何生成迁移 add_references 到不同数据库中的模型

问题描述

我有一个带有两个数据库的 rails 6.1.3.2 应用程序。 我生成一个像这样的脚手架 UserProfile。

rails g scaffold UserProfile image_path:string bio:text user:references

但是user_profiles 表应该在A 数据库中创建,而users 表在B 数据库中。 B 数据库中的用户表已经创建并正在使用。所以我不能移动它。

生成的迁移是这样的。

def change
create_table :user_profiles do |t|
  t.string :nickname
  t.text :bio
  #t.references :user,null: false,foreign_key: true
  t.bigint :user_id,index: true
  t.timestamps
end

评论了 t.references 因为它在我 rake db:migrate 时出错。

PG::UndefinedTable: ERROR:  relation "users" does not exist 
db/migrate/20210520022156_create_user_profiles.rb:3:in `change'

但是如果我像上层迁移代码一样将 t.references 更改为 t.bigint,那么 rake db:migrate 就可以了,而且效果很好。

user = User.first
user.user_profiles.create!(nickname: 'kikiki')

UserProfile Create (1.5ms)  INSERT INTO "user_profiles" ("nickname","user_id","created_at","updated_at") VALUES ($1,$2,$3,$4) RETURNING "id"  [["nickname","kikiki"],["user_id",8],["created_at","2021-05-20 06:29:26.522668"],["updated_at","2021-05-20 
06:29:26.522668"]]

这是设计的还是我做错了什么? 对于另一个数据库中关联模型的“t.references”,ruby on rails 迁移的正确方法是什么?

解决方法

我用这种方式。之前创建 user_profile

rails g AddUserToUserProfile user:references