从表中除去主键中带有外键的引用记录的主键

问题描述 投票:1回答:1

如果唯一标识符是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)
ruby-on-rails ruby rails-migrations
1个回答
1
投票

您可以像这样将表的任何属性称为主键:

create_table :user_profiles, :primary_key => :user_id do |t|
© www.soinside.com 2019 - 2024. All rights reserved.