【问题标题】:how to generate migration add_references to model in different database如何生成迁移 add_references 以在不同数据库中建模
【发布时间】:2021-08-09 09:55:43
【问题描述】:

我有一个带有两个数据库的 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, null: false, 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 迁移的正确方法是什么?

【问题讨论】:

    标签: ruby-on-rails multiple-databases ruby-on-rails-6.1


    【解决方案1】:

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

    rails g AddUserToUserProfile 用户:参考

    【讨论】:

      猜你喜欢
      • 2021-07-15
      • 1970-01-01
      • 2016-06-09
      • 2011-01-21
      • 2015-06-22
      • 2013-04-04
      • 2010-12-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多