views:

21

answers:

1

I have this data structure:

Root
  Child
    Child
  Child
    Child
      Child
  Child

My models are set up like this:

  • Root: has_many :children
  • Child: has_many :children, belongs_to :root

For some tasks every child has a back reference to the Root record.

How can I make sure, every time a new a child gets inserted, the root reference gets updated to?

Currently only the immediate children are set correctly:

  • c = Root.children.new --> root_id is set
  • c.children.new --> root_id is nil (understandably)

I suspect I can only do this manually...

+1  A: 

Manually, yes. But it's still a clear and clean way of expressing what you're trying to do.

c.children.new(:root_id => c.root_id)

jdl
Thank you very much!
DR