2010-12-01 68 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)