【问题标题】:activerecord not like queryactiverecord 不像查询
【发布时间】:2015-06-08 21:03:37
【问题描述】:

我找不到与“Not Like”等效的 activerecord。我能够找到where.not,但这将检查字符串是否与值不匹配,如下所示:

User.where.not(name: 'Gabe')

is the same as:

User.where('name != ?', 'Gabe')

我正在寻找一个 NOT LIKE,其中的值不包含在字符串中。等效的 sql 查询如下所示:

SELECT * FROM users WHERE name NOT LIKE '%Gabe%'

在 ActiveRecord 中,我目前可以摆脱以下情况:

User.where("name NOT LIKE ?", "%Gabe%")

但这还有很多不足之处。 Rails 4 中是否有任何新增功能来促进这一点?

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    好吧,你可以这样做:

    User.where.not("name LIKE ?", "%Gabe%")
    

    注意:这仅在 Rails 4 中可用。

    【讨论】:

      【解决方案2】:

      正如其他人指出的那样,ActiveRecord 没有很好的语法来构建 like 语句。我建议使用 Arel,因为它可以减少特定于数据库平台的查询(将使用 ilike 用于 sqlite 和 like 用于其他平台)。

      User.where(User.arel_table[:name].does_not_match('%Gabe%'))
      

      您也可以将其实现为包含模型实现的范围:

      class User < ActiveRecord::Base
        scope :not_matching, 
          -> (str) { where(arel_table[:name].does_not_match("%#{str}%")) }
      end
      

      【讨论】:

      【解决方案3】:

      很遗憾,ActiveRecord 没有 like 查询生成器。我同意原始的“不喜欢”还有很多不足之处。您可以将其设为范围 (scope :not_like, (column, val) -&gt; { ... }),但 AR 本身并不这样做。

      【讨论】:

        【解决方案4】:

        只是添加了活动记录的“where.not”的答案。 “where.not”也将排除空值。即查询 User.where.not(name: 'Gabe') 将留下名称为 'Gabe' 的记录,但它也排除具有 NULL 值的名称列。所以在这种情况下,解决方案是

        User.where.not(name: 'Gabe') .or(User.where(name: nil))

        【讨论】:

        • 关于 activerecord 的一个(对我而言)完全不直观的“功能”非常重要的一点
        猜你喜欢
        • 1970-01-01
        • 2011-04-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-04
        • 2011-09-02
        相关资源
        最近更新 更多