I have a collection of recipes, each having a number of ingredients. This information is stored in a join table. Give a recipe, I'd like to find recipes similar to it based on ingredients. How would I go about doing this?
A:
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)}
not tested
fl00r
2010-04-09 23:28:51
+5
A:
Let's assume a recipe is considered similar when it has 3 ingredients common with the given recipe.
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
Given a recipe you can get similar recipes as follows:
recipe.similar # 3 similar ingredients
recipe.similar(4) # 4 similar ingredients
KandadaBoggu
2010-04-10 04:27:03
@KandadBoggu +1. This is cool!
macek
2010-04-10 05:30:34