【发布时间】:2016-02-12 12:21:38
【问题描述】:
我正在尝试运行一个脚本来从我们的系统中删除一大群学生,我依靠 rails dependent: :destroy 约定来确保我清理了与这些学生相关的所有数据。
我对这个系统很陌生,但这就是他们在属于student 的student_application 模型中构建has_many 关系的方式。
student.rb 学生模型
has_many :applications, class_name: "StudentApplication", dependent: :destroy
has_many :season_classes, through: :applications
has_many :payments, foreign_key: "student_id", dependent: :destroy
student_application.rb student_application 模型
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
user_application_status.rb user_application_status 模型
belongs_to :application_status
# Student links
belongs_to :student_application
has_one :student, through: :student_application
payment.rb 支付模式
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 文件中找到了这个
--
-- Name: payments_student_application_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY payments
ADD CONSTRAINT payments_student_application_id_fkey FOREIGN KEY (student_application_id) REFERENCES student_applications(id);
我们在数据库中使用 Rails 4.1.14.1 和 Ruby 2.1.6 和 Postgres。关于可能导致此问题的任何想法?
【问题讨论】:
-
你能在用户模型中显示关系设置吗?
-
您找到解决方案或原因了吗?
标签: ruby-on-rails ruby postgresql ruby-on-rails-4