2011-04-10 130 views
0

我正在使用mysql在rails3上實現配方搜索。複雜的搜索設計

搜索的想法是,用戶輸入任意數量的成分和搜索輸出建議做什麼,按產品缺陷順序排序。

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 

什麼是最有效的方式來實現此搜索? 你會推薦什麼寶石或技巧? 謝謝你的答案

回答

1
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 

我設法找到通過創建配方模型等方法解決。