首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >rails依赖::破坏具有错误ID值的工作

rails依赖::破坏具有错误ID值的工作
EN

Stack Overflow用户
提问于 2022-10-25 13:08:10
回答 1查看 35关注 0票数 1

我的schema.db

代码语言:javascript
运行
复制
  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

用户模型

代码语言:javascript
运行
复制
class User < ApplicationRecord
  has_one :pet, foreign_key: :id, dependent: :destroy
end

pet模型

代码语言:javascript
运行
复制
class Pet < ApplicationRecord
  belongs_to :user, optional: true
end

show.erb

代码语言:javascript
运行
复制
    <%= link_to t('delete'), user_path(id: @user.id), method: :delete %>
    <%= link_to t('.pet_delete'), pet_path(@auser.pet_id), method: :delete %>

用户控制器

代码语言:javascript
运行
复制
  def destroy
    User.destroy(params[:id])
    redirect_to users_path
  end

宠物控制器

代码语言:javascript
运行
复制
  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无效删除,但没有工作。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-10-25 13:19:32

问题是您将id指定为外键。

代码语言:javascript
运行
复制
class User < ApplicationRecord
  has_one :pet, foreign_key: :id, dependent: :destroy
end

您需要指定user_id

代码语言:javascript
运行
复制
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应该如下所示:

代码语言:javascript
运行
复制
  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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74194608

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档