2014-01-12 60 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))