Help with search query

ok, here’s my dilemna…i have a site that has a list of item
combinations (aka compounds) for a computer game.

i’m having a hard time coming up with a good way to search a compounds
result and the items that are contained within the compound.

the formulas are setup like:


to get a better idea of what i mean check this page from the site

my table setup is:

ITEMS (which can be a compound result or compound component)

COMPOUNDS (has_many compound_materials)

COMPOUND_MATERIALS (belongs_to item, compound

i guess my first question would be what is the best way that i can
search on ITEM table values like names with the least amount of queries.

i thought about doing joins from compound and compound_materials to
items but i’m sure if it’s possible joining to the same table twice.

at the moment i am doing it this way:

@compounds =…)

@compound_materials =…)

  for compound_material in @compound_materials
    compound = Compound.find(:all, :conditions => [ " =

?", compound_material.compound_id])
@compounds += compound if not compound.blank?


  @compounds.sort! {...}

pretty ugly huh?

hope someone can help since i have been trying to come up with a
solution for a few hours now.