Ruby on rails can';由于外键约束,无法删除对象
我正在尝试执行一个简单的Ruby on rails can';由于外键约束,无法删除对象,ruby-on-rails,postgresql,Ruby On Rails,Postgresql,我正在尝试执行一个简单的user.destroy,但遇到以下错误: 错误:表“用户”上的更新或删除违反了表“标识”上的外键约束“fk_rails_5373344100” 详细信息:键(id)=(2)仍从表“标识”中引用 这是我的身份迁移 class CreateIdentities < ActiveRecord::Migration def change create_table :identities do |t| t.references :user, inde
user.destroy
,但遇到以下错误:
错误:表“用户”上的更新或删除违反了表“标识”上的外键约束“fk_rails_5373344100”
详细信息:键(id)=(2)仍从表“标识”中引用
这是我的身份迁移
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 CreateIdentity
以下是我的用户和身份模型:
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-Identity:provider的唯一性
定义self.find_for_oauth(auth)
查找或创建用户(uid:auth.uid,提供程序:auth.provider)
结束
结束
和用户:
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
class用户TEMP\u email\u REGEX,on::update
...
结束
我不熟悉外键和引用,所以我根本不知道如何解决这个问题。一个简单的解决方案是简单地级联删除关联表中的记录,这可以通过活动记录完成,如下所示: user.rb
class User < ActiveRecord::Base
has_many :identities, dependent: :destroy
# rest of user class
end
class用户
查看以了解更多信息。您需要先删除引用用户的标识。然后您可以删除该用户。。默认情况下,外键执行
限制
,因此,如果有任何内容引用该用户,则无法删除该用户
如果您想使用Rails来处理身份销毁,您可以这样做
class User < ActiveRecord::Base
has_many :identities, dependent: :destroy
......
end
假设rails 4.2具有本机支持太棒了!但只是一件小事,他需要先删除外键,然后使用on_delete::cascade再次添加外键
add_foreign_key :identities, :users, on_delete: :cascade