我有一系列食谱,每种都有许多成分。此信息存储在连接表中。给一个食谱,我想根据成分找到类似的食谱。我该怎么做呢?
答案 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)}
未经测试