首页 > 解决方案 > 从表中删除主键,在rails中使用外键记录引用

问题描述

id如果唯一标识符是user_id外键,我需要我的列吗?我不认为我会查询user_profileby id。原因是我的用户模型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-railsrubyrails-migrations

解决方案


您可以将表的任何属性作为主键,如下所示:

create_table :user_profiles, :primary_key => :user_id do |t|

推荐阅读