Acts_as_tree ... somewhat

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.

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