Ric*_*son 23 postgresql ruby-on-rails
尝试做一个简单的user.destroy但遇到以下错误:
错误:表"user"上的更新或删除违反了表"identities"上的外键约束"fk_rails_5373344100"DETAIL:Key(id)=(2)仍然从表"identity"中引用.
这是我对身份的迁移
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
Run Code Online (Sandbox Code Playgroud)
这是我的用户和身份模型:
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
Run Code Online (Sandbox Code Playgroud)
和用户:
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
Run Code Online (Sandbox Code Playgroud)
我是外键和引用的新手,所以我不确定如何解决这个问题.任何帮助将不胜感激.
谢谢
Doo*_*oon 50
您需要先删除引用该用户的标识.然后你可以删除用户..默认情况下,外键正在执行,restrict所以如果有任何引用的话,你就无法删除用户.
如果您想使用Rails处理破坏您可以做的身份
class User < ActiveRecord::Base
has_many :identities, dependent: :destroy
......
end
Run Code Online (Sandbox Code Playgroud)
这会导致Rails破坏所有依赖记录.
但是,当您使用外键时,可以调整迁移以设置级联删除
add_foreign_key :identities, :users, on_delete: :cascade
Run Code Online (Sandbox Code Playgroud)
假设rails 4.2具有原生支持
| 归档时间: |
|
| 查看次数: |
21642 次 |
| 最近记录: |