Search code examples
mysqlruby-on-rails-3searchsearch-engine

complicated search design


I am implementing a recipe search on rails3 using mysql.

The idea of search is that user enters any number of ingredients and search outputs suggestions what to make, sorted in product deficiency order.

class Recipe < ActiveRecord::Base
  has_many :ingredients
end

# these records will be entered by user
class IngredientType < ActiveRecord::Base
  has_many :ingredients
end

# this table is join table
class Ingredient < ActiveRecord::Base
  belongs_to :ingredient_type
  belongs_to :recipe
end

What would be the most efficient way to implement this search? What gems or techniques would you recommend? Thank you for your answers


Solution

  •   def self.from_ingredients ingredients
        count_sql = Ingredient.
            select('COUNT(*)').
            joins(:recipes_ingredients).
            where('`recipes_ingredients`.`recipe_id` = `recipes`.`id`').
            where('`ingredients`.`id` in (?)', ingredients).to_sql
    
        where("(#{count_sql}) > 0").
            order("((`recipes`.`ingredients_count`) - (#{count_sql})) ASC")
      end
    

    I managed to find solution by creating such method in recipe model.