I've got a model that has a self-referencial join through a join table, as defined below:
class Task < ActiveRecord::Base
has_many :dependency_dependents, foreign_key: :dependency_id, class_name: 'TaskDependency', dependent: :destroy
has_many :dependency_dependencies, foreign_key: :task_id, class_name: 'TaskDependency', dependent: :destroy, autosave: true
has_many :dependencies, through: :dependency_dependencies
has_many :dependents, through: :dependency_dependents, source: :task
end
class TaskDependency < ActiveRecord::Base
belongs_to :task
belongs_to :dependency, class_name: 'Task'
end
Everything with the joins works well. When the record is saved, it performs a bunch of calculations based on the records it depends on, and it then moves on the updating the dependent records which in turn perform the same calculations for those records and so on.
The issue is that if somewhere in the chain of dependent tasks, there is a dependency on a task somewhere else up the tree, firstly the calculations will fail, but most importantly, it'll cause an infinite loop of calculations and updates.
Is there a nice way I can check for this infinite loop before I save a record, (ideally before creating the dependency in the first place).
I'm happy to do this either using pure SQL or ruby, just wondering if anyone has a clean solution for this.
Aucun commentaire:
Enregistrer un commentaire