2011-04-10 2 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 

귀하의 답변 주셔서 감사합니다.

관련 문제