0

我有一个食谱应用程序,其中每个食谱都与许多成分相关联,并且使用祖先宝石组织成分。

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

因此,例如,“酱油”将是一种成分,而“龟甲万”将是“酱油”的子代。一个食谱可能需要“酱油”,或者专门叫出“龟甲万”的名字。

我希望能够按祖先搜索食谱,所以如果我搜索“酱油”,它也会找到孩子“龟甲万”的食谱。我怎样才能用 Rails 魔法做到这一点?

4

1 回答 1

1

如果ingredient_key是给定的成分(酱油),这可以给你所有的食谱:

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

如果您只想要该成分及其子成分的食谱,则可以省略祖先。

于 2014-10-30T18:00:54.447 回答