开发者

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


  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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜