我正在使用 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
实现此搜索的最有效方法是什么? 您会推荐哪些 gem 或技术? 谢谢您的解答
最佳答案
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
我设法通过在配方模型中创建这样的方法来找到解决方案。
关于mysql - 复杂的搜索设计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5612453/