簡體   English   中英

從表中刪除主鍵,在rails中使用外鍵記錄引用

[英]Remove primary key from a table the references record with foreign key in rails

如果唯一標識符是user_id外鍵,我是否需要我的id列? 我不認為我會通過 id 查詢user_profile 原因是我的用戶 model 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|

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM