2010-12-01 114 views

回答

4

如果你只需要搜索記錄,通過ID可以試試這個

class Model 
    def self.not_exists?(ids) 
    self.find(ids) 
    false 
    rescue 
    true 
    end 
end 

如果任何ID不存在find方法將引發的ActiveRecord :: RecordNotFound例外,我們根本抓並返回true。

原諒我的英文:)

22

只需添加一個!運營商

!Model.exists?(:id => [1, 2, 3]) #=> true 
+2

我詢問如何說如果`2`和`3`不存在,如何使它返回false。如果存在`1`,`Model.exists?(:id => [1,2,3])`返回`false`,而我想`Model.not_exists?(:id => [1,2,3] )`返回true,如果有的話不存在。 – 2010-12-01 16:42:17

+1

`Model.find(ids_ary).count`然後`救援ActiveRecord :: RecordNotFound` – 2017-05-31 07:40:30

1
class Model 
    def self.does_not_exist?(ids) 
    Model.where(id: ids).count < ids.size 
    end 
end 

解釋:如果(且僅當)所有的情況下,你要尋找的存在,Model.where(id: ids).count等於ids.size

但是,如果有一個或多個實例丟失,計數將會降低,這意味着有一條不存在的記錄。

+2

可能對於解釋更有幫助 – R3tep 2015-04-22 08:53:23

-1

另一個簡單的方法是使用where方法和一個id數組。

# If the count of the query is equal to the count of all of the id's then the statement will return false. 
# Else it will return true if not all ids exists in the database. 
Model.where(id: [1, 2, 3]).count < [1,2,3].count 
1

使用empty?,這就是你想要的。它使用count(*) vs select 1 as one

> Rocketeer.where(:id => [1, 2, 3]).empty? 
    (0.6ms) SELECT COUNT(*) FROM "rocketeers" WHERE "rocketeers"."id" IN (1, 2, 3) 
=> false 

> Rocketeer.where(:id => [1, 2, 3]).any? 
    (0.5ms) SELECT COUNT(*) FROM "rocketeers" WHERE "rocketeers"."id" IN (1, 2, 3) 
=> true 

> Rocketeer.where(:id => [1, 2, 3]).exists? 
    Rocketeer Exists (0.5ms) SELECT 1 AS one FROM "rocketeers" WHERE "rocketeers"."id" IN (1, 2, 3) LIMIT 1 
=> true 
0

這樣做是使用unlessexists?的更紅寶石去年秋季的方式。這樣,您不必使用!。我想,你的使用情況是這樣的:

def my_method 
    return unless Model.exists?(:id => [1, 2, 3]) 

    # do something 
end 

您可以替換1, 2, 3與變量(稱之爲id或東西),甚至完全消除陣列,如果你想:.exists?(id: id)