【问题标题】:Rails: update_attributes not honoring dependent: :destroyRails:update_attributes 不尊重依赖::destroy
【发布时间】:2019-09-20 14:37:32
【问题描述】:

当我使用 update_attributes 时,它应该删除某些条目并删除它们的依赖项(因为我使用依赖项::destroy)。但是,我收到外键错误,不知道该怎么做。

我有以下

class StudentGoal < ApplicationRecord
    belongs_to :goal
    belongs_to :student
    has_many :student_goal_scores, dependent: :destroy
end

class StudentGoalScore < ApplicationRecord
    belongs_to :student_goal
end

class Goal < ApplicationRecord
    has_many :student_goals, dependent: :destroy
    has_many :students, through: :student_goals
end

在 Rails 控制台中,如果我运行以下命令(目标之前有多个学生与之关联):

Goal.find(2).update_attributes(students: [Student.find(69)])

我收到以下错误

ActiveRecord::InvalidForeignKey (PG::ForeignKeyViolation: ERROR:  
update or delete on table "student_goals" violates foreign key constraint 
"fk_rails_bcae4e177a" on table "student_goal_scores") DETAIL:  Key (id)=(49) is 
still referenced from table "student_goal_scores".

如果我只是尝试使用 StudentGoal.find(number).destroy 销毁 StudentGoal,则会正确删除 StudentGoalScores。

我可以做些什么来使 update_attributes 正确地级联删除吗?

【问题讨论】:

  • 你可以使用 depedent: :destroy, prepend: true

标签: ruby-on-rails postgresql activerecord foreign-keys cascade


【解决方案1】:

效果很好,就像documentation states:

:依赖

控制关联对象在其所有者被销毁

时发生的情况

update 不应删除任何内容。

编辑:Rails 自动处理连接表(如 StudentGoal),这意味着您无需担心在更新关联表时删除/更新该表(Goal.find(2).update_attributes(students: [Student.find(69)]但是 ,在您的情况下,您在连接表 (has_many :student_goal_scores) 中设置了一个 FK,以及相应的 DB 约束。

这就是问题所在。 Rails 尝试更新 Goal/Student 关联,但 DB 抱怨,因为这将留下孤儿 StudentGoalScore 记录。

您可以将StudentGoalScore 列移动到StudentGoal 或在StudentGoal 中设置回调以自动删除StudentGoalScore

【讨论】:

  • update_attributes 当前确实尝试删除,这是有道理的,因为我正在删除一些依赖项(例如,将学生从学生 2 和 3 更改为仅学生 2)。我希望这个删除级联(破坏)。所以是的,更新应该删除一些东西。我只是需要它来破坏东西,但不知道如何。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-29
  • 2019-03-19
  • 1970-01-01
  • 2013-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多