我可以这样做来检查记录是否存在(如果存在“1”,但“2”和“3”不存在):
Model.exists?(:id => [1, 2, 3]) #=> true
我该怎么做,所以:
Model.not_exists?(:id => [1, 2, 3]) #=> true
如果您只需要通过ID搜索记录,您可以试试这个
class Model
def self.not_exists?(ids)
self.find(ids)
false
rescue
true
end
end
如果任何ID不存在,find
方法将引发一个ActiveRecord :: RecordNotFound异常,我们只是捕获并返回true。
请原谅我的英文:)
只需添加一个!操作者
!Model.exists?(:id => [1, 2, 3]) #=> true
class Model
def self.does_not_exist?(ids)
Model.where(id: ids).count < ids.size
end
end
说明:如果(且仅当)您要查找的所有实例都存在,则Model.where(id: ids).count
等于ids.size
。
但是,如果缺少一个或多个实例,则计数将更低,这意味着存在不存在的记录。
使用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
更像Ruby的方式是使用unless
和exists?
。这样,您就不必使用!
。我想你的用例是这样的:
def my_method
return unless Model.exists?(:id => [1, 2, 3])
# do something
end
您可以用变量替换1, 2, 3
(称之为id
或其他东西),如果您愿意,甚至可以完全删除数组:.exists?(id: id)
另一种简单的方法是使用带有id数组的where方法。
# 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