【问题标题】:Check if record does NOT exist in Rails (from array of ids)?检查 Rails 中是否不存在记录(来自 id 数组)?
【发布时间】:2010-12-01 16:28:41
【问题描述】:

我可以这样做来检查记录是否存在(比如 id “1”存在,但“2”和“3”不存在):

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

我该如何做相反的事情,所以:

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

【问题讨论】:

    标签: sql ruby-on-rails


    【解决方案1】:

    只需添加一个!运营商

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

    【讨论】:

    • 我在问如果2 和3 不存在,如何让它返回false。如果1 存在,!Model.exists?(:id => [1, 2, 3]) 返回 false,而如果不存在,我希望 Model.not_exists?(:id => [1, 2, 3]) 返回 true。
    • Model.find(ids_ary).count 然后rescue ActiveRecord::RecordNotFound
    【解决方案2】:

    如果你只需要通过ID搜索记录你可以试试这个

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

    如果任何 ID 不存在,find 方法将引发 ActiveRecord::RecordNotFound 异常,我们只需捕获并返回 true。

    对不起,我的英语:)

    【讨论】:

    • 这不应该是公认的答案,因为它的使用是危险的救援,find 将加载您只关心原始存在的记录。答案应该是被接受的
    【解决方案3】:

    使用empty?,这就是你想要的。它使用count(*) 与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
    

    【讨论】:

    • SELECT 1 AS one ... LIMIT 1 不是比SELECT COUNT(*) 更有效率吗?
    • limit 1 等于或快于count(*)。虽然通常它只能通过表大小和索引键的组合来感知。此外,如果您要使用匹配记录,请使用empty? 来保存 DB RTT。
    【解决方案4】:
    class Model
      def self.does_not_exist?(ids)
        Model.where(id: ids).count < ids.size
      end
    end
    

    说明:如果(且仅当)您要查找的所有实例都存在,Model.where(id: ids).count 等于ids.size。

    但是,如果缺少一个或多个实例,则计数会更低,这意味着有一条不存在的记录。

    【讨论】:

    • 或许解释一下会更有帮助
    • 它回答了这个问题,但对大量行来说性能较慢。它在 SQL 中执行 COUNT 计算表中的每一行。另一方面,where(id: [1, 2, 3]).exists? 执行SELECT... WHERE... LIMIT 1,它将返回它找到的第一行。请参阅@mwoods79 的answer。
    【解决方案5】:

    一种更符合 Ruby 风格的方法是使用 unless 和 exists?。这样,您就不必使用!。我想你的用例是这样的:

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

    您可以将 1, 2, 3 替换为变量(称其为 id 或其他名称),如果您愿意,甚至可以完全删除数组:.exists?(id: id)

    【讨论】:

      【解决方案6】:

      另一种简单的方法是使用带有 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
      

      【讨论】:

        猜你喜欢
        • 2021-08-08
        • 1970-01-01
        • 2013-08-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-22
        • 2013-05-16
        • 1970-01-01
        相关资源
        最近更新 更多