# Object relations in memory

**URL:** <https://www.ruby-forum.com/t/object-relations-in-memory/125378>\
**Category:** Rails\
**Created:** [January 8, 2008, 6:07pm UTC](https://www.ruby-forum.com/t/object-relations-in-memory/125378 "2008-01-08T18:07:27Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![xinit](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/x/9f8e36/32.png) [@xinit](https://www.ruby-forum.com/u/xinit)\
**Post date:** [January 8, 2008, 6:07pm UTC](https://www.ruby-forum.com/t/object-relations-in-memory/125378/1 "2008-01-08T18:07:27Z")

</div>

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?
