我的schema.db
create_table 'pet', force: :cascade do |t|
t.string 'name'
t.datetime 'created_at', precision: 6, null: false
t.datetime 'updated_at', precision: 6, null: false
end
create_table 'user', force: :cascade do |t|
t.string 'name'
t.references :pet, index: true, foreign_key: { on_delete: :nullify }
t.datetime 'created_at', precision: 6, null: false
t.datetime 'updated_at', precision: 6, null: false
end
用户模型
class User < ApplicationRecord
has_one :pet, foreign_key: :id, dependent: :destroy
end
pet模型
class Pet < ApplicationRecord
belongs_to :user, optional: true
end
show.erb
<%= link_to t('delete'), user_path(id: @user.id), method: :delete %>
<%= link_to t('.pet_delete'), pet_path(@auser.pet_id), method: :delete %>
用户控制器
def destroy
User.destroy(params[:id])
redirect_to users_path
end
宠物控制器
def destroy
Pet.destroy(params[:id])
redirect_to users_path
end
问题:如果我用宠物id 5删除用户id 5,则依赖销毁操作良好,它会删除(用户id 5)和(宠物id 5)。
如果我的用户id 5与宠物id为0,而用户id 4为宠物id 5,则当我删除用户id 5时,用户5与用户4的宠物(宠物id 5)一起被删除,因此剩余的结果是->用户id 5删除,用户id 4有0宠物。
出了点问题,但我找不到问题所在。依赖破坏只能在同一时间内找到相同的userId和petId。
我期望如果我删除用户id 3与宠物id 1,想要删除好我尝试了改变位置的依赖销毁(在宠物模型),更改模式.‘s的on_delete无效删除,但没有工作。
发布于 2022-10-25 13:19:32
问题是您将id
指定为外键。
class User < ApplicationRecord
has_one :pet, foreign_key: :id, dependent: :destroy
end
您需要指定user_id
:
class User < ApplicationRecord
has_one :pet, foreign_key: :user_id, dependent: :destroy
end
但是,在这种简单的情况下,您根本不需要指定外键。只要在user_id
表中有一个名为pets
的列,它就能正常工作,因为Rails自动假定外键应该是<model>_id
。
另外,请记住外键应该添加到子,而不是父。因此,您需要将user_id
添加到pets
表,而不是将pet_id
添加到users
表。
最后,您的schema.rb
应该如下所示:
create_table 'pet', force: :cascade do |t|
t.string 'name'
t.datetime 'created_at', precision: 6, null: false
t.datetime 'updated_at', precision: 6, null: false
t.references :user, index: true, foreign_key: { on_delete: :nullify } # <== this should be added
end
create_table 'user', force: :cascade do |t|
t.string 'name'
# t.references :pet, index: true, foreign_key: { on_delete: :nullify } <== this should be removed
t.datetime 'created_at', precision: 6, null: false
t.datetime 'updated_at', precision: 6, null: false
end
https://stackoverflow.com/questions/74194608
复制相似问题