sql - Rails 查询同一字段上的多个条件

标签 sql ruby-on-rails ruby postgresql activerecord

我有两个模型,RecipesSkills。在这种情况下,技能是一种 cooking 技术,例如烘烤、油炸等。因此每个食谱都有一组特定的相关技能。

我想搜索所有这样的食谱:

  1. 查找使用任何给定技能集的所有食谱(例如烘焙煎炸或两者)
    编辑:这不应该返回需要搜索查询中没有的技能的食谱 - 例如如果我搜索技能 [1, 2],我不想要使用技能 [1, 2, 4] 或任何其他超集的食谱。

  2. 如果您向搜索添加新技能,则仅返回其他食谱(例如,如果您将 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/

相关文章:

ruby-on-rails - 同时使用 has_one 和 has_many 关联

ruby - 初始化冰糕时如何忽略某些目录?

MySQL按总重量排序结果

即使 SQL 表列不为空,PHP 表单也会更新 SQL 表

java - Rails 类似于 Java 的数据库抽象

ruby-on-rails - 基于自连接的 Ruby on Rails 路由

php - 将数据传送到移动设备的最轻/最快的方式是什么?

SQL 服务器 : Is it necessary to disable SA user for security issues?

ruby-on-rails - 默认情况下如何使用字符串键创建哈希

ruby-on-rails - 如何验证 Rails 中的日期?