我有一系列食谱,每一个都有许多成分。此信息存储在连接表中。给个菜谱,我想根据成分找到类似的菜谱。我该怎么做呢?
问问题
686 次
2 回答
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
于 2010-04-10T04:27:03.893 回答
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)}
未测试
于 2010-04-09T23:28:51.923 回答