使用ruby根据它们含有的成分找到类似的食谱

时间:2010-04-09 22:22:27

标签: ruby-on-rails ruby nearest-neighbor

我有一系列食谱,每种都有许多成分。此信息存储在连接表中。给一个食谱,我想根据成分找到类似的食谱。我该怎么做呢?

2 个答案:

答案 0 :(得分:9)

我们假设一个配方在有3种常见成分时被认为是相似的。

class Recipe < ActiveRecord::Base
  has_many :recipe_ingredients

  # with three similar ingredients
  def similar(n=3)
    Recipe.find(
      RecipeIngredient.count(
        :joins      => "join recipe_ingredients B ON B.recipe_id = #{self.id}",
        :conditions => "recipe_ingredients.recipe_id != B.recipe_id AND
                        recipe_ingredients.ingredient_id = B.ingredient_id",
        :group      => "recipe_ingredients.recipe_id",
        :having     => "count(*) >= #{n}"
      ).keys
    )
  end
end

class RecipeIngredient  < ActiveRecord::Base
  belongs_to :recipe
  belongs_to :ingredient
end

class Ingredient < ActiveRecord::Base
  has_many :recipe_ingredients
end

鉴于食谱,您可以获得如下相似的食谱:

recipe.similar    # 3 similar ingredients
recipe.similar(4) # 4 similar ingredients

答案 1 :(得分:0)

recipe = Reciepe.first
ingredients = recipe.ingredients
# Find out reciepes with at least one ingredient similar
reciepes = ingredients.each{|in| in.reciepes}
# find out reciepes with at least {count %} ingredients similar
count = 0.5 # 50%
number = (count*ingredients.size).to_i
more_recipies = recipies.select{|r| (r.ingridients&ingredients).size >= number)}

未经测试