Do I need my id
column if the unique identifier is the user_id
foreign key? I dont think I would ever query the user_profile
by id. The reason is that my User model has_one :user_profile
and my user_profile belongs_to :user
楷模
class User < ApplicationRecord
has_one :user_profile
end
class UserProfile < ApplicationRecord
belongs_to :user
end
用户个人资料迁移
class CreateUserProfiles < ActiveRecord::Migration[6.0]
def change
create_table :user_profiles do |t|
t.string :first_name
t.string :last_name
t.timestamps
end
end
end
class AddUserReferenceColumnToUserProfilesTable < ActiveRecord::Migration[6.0]
def change
add_reference :user_profiles, :users, index: false, foreign_key: true
end
end
Postgres user_profiles表
Table "public.user_profiles"
Column | Type | Collation | Nullable | Default
------------+--------------------------------+-----------+----------+-------------------------------------------
id | bigint | | not null | nextval('user_profiles_id_seq'::regclass)
first_name | character varying | | |
last_name | character varying | | |
created_at | timestamp(6) without time zone | | not null |
updated_at | timestamp(6) without time zone | | not null |
users_id | bigint | | |
Indexes:
"user_profiles_pkey" PRIMARY KEY, btree (id)
Foreign-key constraints:
"fk_rails_1e573f2ed5" FOREIGN KEY (users_id) REFERENCES users(id)