how to generate migration add_references to model in different database

258 Views Asked by At

I have a rails 6.1.3.2 application with two databases. I generated a scaffold UserProfile like this.

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

but user_profiles table should be created in A database, but users table is in B database. Users table in B database is already maden and is being used. So I can not move it.

The generated migration is like this.

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

I commented the t.references because it makes an error when I rake db:migrate.

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

but If I change t.references to t.bigint like upper migration codes, rake db:migrate is ok and it works well.

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"]]

Is this designed or Is there anything I did wrong? what is the right way in ruby on rails migration for 't.references' for associated model in another database?

1

There are 1 best solutions below

0
LihnNguyen On

I use this way.create user_profile before

rails g AddUserToUserProfile user:references