我有两个模型,Recipes
和 Skills
。在这种情况下,技能是一种 cooking 技术,例如烘烤、油炸等。因此每个食谱都有一组特定的相关技能。
我想搜索所有这样的食谱:
查找使用任何给定技能集的所有食谱(例如
烘焙
或煎炸
或两者)
编辑:这不应该返回需要搜索查询中没有的技能的食谱 - 例如如果我搜索技能 [1, 2],我不想要使用技能 [1, 2, 4] 或任何其他超集的食谱。如果您向搜索添加新技能,则仅返回其他食谱(例如,如果您将
Boiling
添加到之前的Baking
或油炸
,您现在可以 cooking 多少种新食谱?)
我目前在 Rails 中使用普通的旧 Ruby 方法进行此工作:
class Recipe < ActiveRecord::Base
has_many :practices
has_many :skills, through: :practices
def self.find_recipes_that_require_any_of_these_skills(*known_skill_ids)
self.select do |recipe|
recipe.skill_ids.all? do |skill_id|
known_skill_ids.include?(skill_id)
end
end
end
# calls the above method twice, once with the new skill and once without
# and subtracts one result from the other
def self.find_newly_unlocked_recipes(*prior_skill_ids, new_skill_id)
self.find_recipes_that_require_any_of_these_skills(*(prior_skill_ids + [new_skill_id])) - self.find_recipes_that_require_any_of_these_skills(*prior_skill_ids)
end
end
在 Rails 控制台中:Recipe.find_recipes_that_require_any_of_these_skills(1,4)
返回技能 1、技能 4 或技能 1 和 4 的所有配方对象。
但这效率很低,因为它会为数据库中的每个菜谱生成一个 SQL 查询。
如何以 ActiveRecord/SQL 方式编写这些查询?
最佳答案
def self.find_recipes_that_require_any_of_these_skills(*known_skill_ids)
self.includes(:skills).where(skills: { id: known_skill_ids })
end
关于sql - Rails 查询同一字段上的多个条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22673106/