【发布时间】: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