kid_drew
kid_drew

Reputation: 3995

Rails ancestry association

I have a recipe app where each recipe is associated with a number of ingredients and the ingredients are organized using the ancestry gem.

class Ingredient < AR::Base
  has_ancestry
  has_many :recipe_ingredients
  has_many :recipes, through: :recipe_ingredients
end

class Recipe < AR::Base
  has_many :recipe_ingredients
  has_many :ingredients, through: :recipe_ingredients
end

So, for example, "soy sauce" would be an ingredient and "kikkoman" would be a child of "soy sauce". A recipe might call for "soy sauce" or specifically call out "kikkoman" by name.

I want to be able to search recipes by ancestry, so if I ran a search for "soy sauce" it would also find recipes with the child "kikkoman". How can I accomplish this with Rails magic?

Upvotes: 0

Views: 240

Answers (1)

Anand
Anand

Reputation: 3760

if ingredient_key is the given ingredient (soy sauce), this could give you all recipes:

(ingredient_key.ancestors + ingredient_key + ingredient_key.descendants).map(&:recipes).flatten.uniq .

You could omit ancestors if you only wanted recipes of that ingredient and its children.

Upvotes: 1

Related Questions