【问题标题】:Remove primary key from a table the references record with foreign key in rails从表中删除主键引用记录与rails中的外键
【发布时间】:2020-05-18 03:17:05
【问题描述】:

如果唯一标识符是 user_id 外键,我是否需要我的 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】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-02
      • 1970-01-01
      相关资源
      最近更新 更多