Rails 4依赖于通过嵌套关系进行破坏

时间:2016-02-12 12:21:38

标签: ruby-on-rails ruby postgresql ruby-on-rails-4

我正在尝试运行一个脚本来从我们的系统中删除一大堆学生,我依靠rails dependent: :destroy约定来确保我清理所有与这些相关的数据生。

我对这个系统很陌生,但这就是他们如何构建属于has_many的{​​{1}}模型中的student_application关系。

student.rb 学生模型

student

student_application.rb student_application模型

has_many :applications, class_name: "StudentApplication", dependent: :destroy
has_many :season_classes, through: :applications
has_many :payments, foreign_key: "student_id", dependent: :destroy

user_application_status.rb user_applicaton_status模型

belongs_to :student, touch: true
has_many :user_application_statuses, -> { order(id: :asc) }, dependent: :destroy
has_many :user_application_tasks, through: :user_application_statuses
has_many :file_upload_tasks, through: :user_application_statuses, class_name: "Tasks::FileUploadTask", source: :user_application_tasks
has_many :payment_tasks, through: :user_application_statuses, class_name: "Tasks::PaymentTask", source: :user_application_tasks
has_many :payments, through: :payment_tasks

payment.rb 付款模式

belongs_to :application_status

# Student links
belongs_to :student_application
has_one :student, through: :student_application

当我删除用户时,我收到此错误

belongs_to :student
has_one :payment_task, class_name: "Tasks::PaymentTask"
has_many :transactions

起初我以为在更深层次的关系层面上有一个被遗漏的对象。但据我所知,从查看表和源代码可以看出代码中没有PG::ForeignKeyViolation: ERROR: update or delete on table "student_applications" violates foreign key constraint "payments_student_application_id_fkey" on table "payments" DETAIL: Key (id)=(24747) is still referenced from table "payments". : DELETE FROM "student_applications" WHERE "student_applications"."id" = $1 (0.3ms) ROLLBACK ActiveRecord::InvalidForeignKey: PG::ForeignKeyViolation: ERROR: update or delete on table "student_applications" violates foreign key constraint "payments_student_application_id_fkey" on table "payments" DETAIL: Key (id)=(24747) is still referenced from table "payments". : DELETE FROM "student_applications" WHERE "student_applications"."id" = $1 引用,但我在payments_student_application_id_fkey文件中找到了这个

structure.sql

我们正在使用Rails 4.1.14.1和Ruby 2.1.6以及Postgres作为数据库。关于什么可能导致这个问题的任何想法?

1 个答案:

答案 0 :(得分:2)

从我所看到的......

# in pseudocodes
user has_one or has_many student_application dependent destroy
student_application belongs to a user
student_application has_many payments

因此,删除用户也会导致关联的student_application被删除...但是student_application的id正在从支付表中引用,因此导致错误。

我可以看到两个现成的解决方案:

1)同时为dependent: :destroy(或student_application)的payments模型设置payment_tasks。这将确保付款也会被删除。

但是,如果您不希望出现这种情况......那么选项2:

2)在dependent: :nullify模型上为student_application设置payments。这将确保``student_application_id column on the associated付款object to the deleted student_application`设置为null,以防止出现上述错误。

  

:dependent控制销毁关联父级时关联对象会发生什么。 dependent can be found here的更多选项。