我试图做一个简单的user.destroy,但遇到了以下错误:

错误:表"用户"上的更新或删除违反了表"标识"上的外键约束"fk_rails_5373344100"

这是我的身份迁移

class CreateIdentities < ActiveRecord::Migration
  def change
    create_table :identities do |t|
      t.references :user, index: true, foreign_key: true
      t.string :provider
      t.string :uid

      t.timestamps null: false
    end
  end
end

以下是我的用户和身份模型:

class Identity < ActiveRecord::Base
  belongs_to :user

  validates_presence_of :uid, :provider
  validates_uniqueness_of :uid, :scope => :provider

  def self.find_for_oauth(auth)
    find_or_create_by(uid: auth.uid, provider: auth.provider)
  end
end

和用户:

class User < ActiveRecord::Base
  TEMP_EMAIL_PREFIX = 'ricky@writeit.com'
  TEMP_EMAIL_REGEX = /\ricky@writeit.com/

  # Include default devise modules. Others available are:
  # :lockable, :timeoutable
  devise :database_authenticatable, :registerable, :confirmable,
         :recoverable, :rememberable, :trackable, :validatable, :omniauthable

  validates_format_of :email, :without => TEMP_EMAIL_REGEX, on: :update
...

end

我不熟悉外键和引用,所以我根本不知道如何修复它.

推荐答案

您需要先删除引用该用户的标识.然后你可以删除这个用户..默认情况下,外键为restrict,因此如果有任何引用,则无法删除该用户.

如果您想使用Rails来处理身份销毁,您可以这样做

class User < ActiveRecord::Base
  has_many :identities,  dependent: :destroy 

  ......

 end 

这将导致Rails销毁所有相关记录.

但在使用外键时,可以调整迁移以设置级联删除

 add_foreign_key :identities, :users, on_delete: :cascade

假设rails 4.2具有本机支持

Postgresql相关问答推荐

转换失败:(—122.763091,49.04676)转换为地理(位置)""

PostGresql :正则表达式 Select 其中只有一个正斜杠的行

无法将 json 范围读取为 pgtype.Int4range

PostgreSQL bytea 网络流量双倍预期值

Postgres 会话处于空闲状态,query = COMMIT 或 ROLLBACK

如何获得区间的绝对值

PostgreSQL - 改变数字的精度?

Hibernate 将用户模型保存到 Postgres

如何为 JavaEE 应用程序中的 PostgreSQL 热备设置配置连接故障转移?

psql中set、\set和\pset的区别

PostgreSQL 中的 DATEADD 等效项

在 postgres 中删除所有共享相同前缀的表

在 Postgresql 中获取星期几

sql语句错误:column .. does not exist

PostgreSQL 表变量

在 PGAdmin 中搜索所有功能的文本

防止 PostgreSQL 中的递归触发器

处理用户发送的string contains null byte

在布尔字段上添加索引

postgresql DB中唯一键的正确数据类型是什么?