Hi all!
I have the following situation:
I'm creating an application where I have groups that can contain groups. I do in the following way:
class Group < ActiveRecord::Base belongs_to :group, :class_name => 'Group', :foreign_key => 'group_id' has_many :groups, :class_name => 'Group', :foreign_key => 'group_id' end
This works very well. I can do group.groups and group.group stuff.
The problem with this situation is that it's possible to create cycles:
Group A belongs_to --> Group B belongs_to --> Group C belongs_to --> Group A
Now, I created a method of checking for cycles and added this to my Group model, so I can ask if specific model object creates a cycle. So far so good..
Since I don't want to have cycles in my application, I want to check for cycles before I save the model, so I want to use my check method as a validator. The problem I'm facing is that when I create a model, the whole relational model of objects isn't reflected in memory.
The following happens (let's say I want to update a model). I create 3 groups that form a cycle as above and save them to the database. Now I load group C and do a c.group = nil. This should break the cycle, but when calling c.cycle?, I still get that C causes a cycle. On inspection of group A, I get that A.groups still includes group C.
Since I want to use the check for validation, I don't want to save to the database before I'm sure that there are no cycles.
Is there a way to overcome this?