我有一套食谱,每个食谱都有很多配料。此信息存储在联接表中。给一个菜谱,我想找到类似的菜谱,它的基础上的配料。我该怎么做呢?
最佳答案
假设一个菜谱有三种常见成分时被认为是相似的。
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