• 检查对象存在性


    如果你仅仅想检查一条记录是否存在,可以使用 exists? 方法。这个方法会像 find 方法一样查询数据库,但是它返回的是 true 或者 false 。

    Client.exists?(1)

    exists? 方法可以接受多个 id 作为参数,但是注意只要任何一条记录存在它都会返回 true 。

    Client.exists?(1,2,3)  或者  Client.exists?([1,2,3]}

    直接在一个 model 或者 relation 实例上调用不带参数的 exists? 方法也是可以的。

    Client.where(:first_name => ‘Ryan’).exists?

    上面的例子中,如果至少有一个 first_name 为 ‘Ryan’ 的 client 记录存在,那就会返回 true ,否则就返回 false 。

    Client.exists?

    如果 client 表为空,就返回 false ,否则返回 true 。

    你也可以使用 any? 或者 many? 来检查一个 model 或者 relation 的存在性。

    1. model
      Post.any?
      Post.many?
    1. 已定义的作用域
      Post.recent.any?
      Post.recent.many?
    1. relation
      Post.where(:published => true).any?
      Post.where(:published => true).many?
      1. association
        Post.first.categories.any?
        Post.first.categories.many?
  • 相关阅读:
    正则表达式 \n和\r
    【转】单循环赛赛程安排算法研究
    Iterator效率
    Map获取键值
    PL/SQL语法详解(pdf)
    Iterator模式
    测试js函数的静态页面
    【转】java的一些基本概念
    Oracle 11g用户解锁
    oracle官方文档
  • 原文地址:https://www.cnblogs.com/qinyan20/p/3643256.html
Copyright © 2020-2023  润新知