Moe Moe - 10 months ago 41
Ruby Question

Using ruby to find similar recipes based on ingredients they contain

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?

Answer Source

Let's assume a recipe is considered similar when it has 3 common ingredients.

class Recipe < ActiveRecord::Base
  has_many :recipe_ingredients

  # with three similar ingredients
  def similar(n=3)
        :joins      => "join recipe_ingredients B ON B.recipe_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}"

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

class Ingredient < ActiveRecord::Base
  has_many :recipe_ingredients

Given a recipe you can get similar recipes as follows:

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