# Acts\_as\_tree ... somewhat

**URL:** <https://www.ruby-forum.com/t/acts-as-tree-somewhat/115409>\
**Category:** Rails\
**Created:** [September 25, 2007, 12:27am UTC](https://www.ruby-forum.com/t/acts-as-tree-somewhat/115409 "2007-09-25T00:27:43Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Lucas\_HSSSSngaro](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/b38774/32.png) [@Lucas\_HSSSSngaro](https://www.ruby-forum.com/u/Lucas_HSSSSngaro)\
**Post date:** [September 25, 2007, 12:27am UTC](https://www.ruby-forum.com/t/acts-as-tree-somewhat/115409/1 "2007-09-25T00:27:43Z")

</div>

Hello folks.

I’m having some trouble here, hope you can help me =D.

I have two associated models: Product and Recipe.

A Recipe is… a recipe, showing the components of a Product… which  
are Products too.

So, the table structure is:

Products  
id  
name  
unity\_id  
(…)

Recipes  
id  
product\_id (the parent\_id, a product)  
child\_id (the child\_id, also a product)  
quantity  
(…)

The table recipes is a tree structure. Sometimes the user may want to  
retrieve the complete “recipe” of one or more products. I’ve tried to  
use acts\_as\_tree but I’m getting some weird behaviors, such as  
infinite loops depending on the tree structure. I guess it’s because I  
don’t use the “id” of the recipes table as one of the keys in the  
relationship. Acts\_as\_tree allows me to configure the parent\_id column  
(which I’ve set to product\_id), but it still doesn’t work, I think  
that I need to let it know about child\_id…

So, anyone knows how to make this work?

PS: here are the models code

class Recipe \< ActiveRecord::Base  
acts\_as\_tree :foreign\_key =\> ‘product\_id’

belongs\_to :products,  
:class\_name =\> “Product”,  
:foreign\_key =\> “product\_id”

belongs\_to :children,  
:class\_name =\> “Product”,  
:foreign\_key =\> “child\_id”  
end

class Product \< ActiveRecord::Base  
has\_many :recipes  
has\_many :children, :through =\> :recipes, :foreign\_key =\> :child\_id

has\_many :fathers, :through =\> :recipes, :foreign\_key =\> :product\_id  
end

Thanks in advance.

---

<div class="post-metadata">

**Author:** ![Lucas\_HSSSSngaro](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/b38774/32.png) [@Lucas\_HSSSSngaro](https://www.ruby-forum.com/u/Lucas_HSSSSngaro)\
**Post date:** [September 25, 2007, 10:21pm UTC](https://www.ruby-forum.com/t/acts-as-tree-somewhat/115409/2 "2007-09-25T22:21:56Z")

</div>

acts\_as\_tree is meant for self-referential tables (ie. A Recipie that  
has child Recipes) Think, What is hierarchical in nature that you’re  
modeling? I believe what you want is this:

Table structure:

Products  
id  
parent\_id  
name

Recipes  
id  
product\_id  
quantity

class Product \< ActiveRecord::Base  
acts\_as\_tree  
has\_many :recipes  
end

class Recipe \< ActiveRecord::Base  
belongs\_to :product  
end
