2014-01-12 25 views
1

我是rails新手,甚至是红宝石,所以我在解决这个问题时遇到了一些麻烦。在rails中相互减去两个查询

我想找出两个查询之间的区别。这个特定的查询应该返回一个单独的记录,因为我已经设置了它,使得食谱缺少食谱中的一个ID。 当前代码:

q = Recipe.all - Recipe.where(recipe_id: recipes) 

其中recipes是一个ID数组。

从我对语言的有限理解来看,如果Recipe.all和Recipe.where都返回数组,就可以工作。

我花了一些时间在网上搜索,没有任何东西来帮助我。

我试过

其他的事情:

q = [Recipe.all] - [Recipe.where(recipe_id: recipes)] 
q = Recipe.where.not(recipe_id: recipes) # Wouldn't work because the array is the one with the extra id 

虽然没有证明有帮助的。

+0

原来我是在问错误的问题。由于ID数组是具有额外记录的数组,我应该将该数组的差异与Recipe.where的结果进行比较。我不知道如何修正这个问题,但我会将答案放在答案中。 – Cereal

回答

1

原来我问错误的问题。

由于ID数组是一个具有额外元素,而不是数据库查询,我应该比较它与查询的差异。

我的回答如下:

q = recipes - Recipe.where(recipe_id: recipes).ids 

它返回缺少的ID。

+0

很好的答案。这真的很有帮助。谢谢 :) –

3

试试这个:

q = Recipe.where('recipe_id NOT IN (?)', recipes) 
0

如果您使用Rails 4,你可以使用not query method

q = Recipe.where.not(id: recipes) 

这将发电机下面的查询:

SELECT "recipes".* FROM "recipes" WHERE ("recipes"."id" NOT IN (12, 8, 11, 5, 6, 7))