如果唯一标识符是id
外键,我是否需要user_id
列?我认为我永远不会通过ID查询user_profile
。原因是我的用户模型has_one :user_profile
和我的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)
您可以像这样将表的任何属性称为主键:
create_table :user_profiles, :primary_key => :user_id do |t|