【问题标题】:Rails 3: scope is not trueRails 3:范围不正确
【发布时间】:2011-10-12 02:46:11
【问题描述】:

如何将以下内容转换为适用于 sqlite 和 mysql 的内容?注意,internal 可以为空。

  scope :external, where("internal is not true")

(在 Rails 4 中,可以简单地使用:)

  scope :external, where.not(internal: true)

【问题讨论】:

    标签: ruby-on-rails arel


    【解决方案1】:

    ActiveRecord 足够聪明,可以做到这一点,只需这样做:

    scope :external, where(internal: [false, nil])
    

    这将被转换为类似的 SQL(可能带有表名和 quetes):

    • 用于 PostgreSQL 和 SQLite internal IN ('f') OR internal IS NULL
    • 对于 MySQL internal IN (0) OR internal IS NULL

    如果需要更多控制,您可以使用 Arel:

    scope :external,
      where(arel_table[:internal].eq(false).or(arel_table[:internal].eq(nil)))
    

    应该是:

    • 对于 PostgreSQL 和 SQLite internal = 'f' OR internal IS NULL
    • 对于 MySQL internal = 0 OR internal IS NULL

    请记住,如果您需要在 SQL 中检查 NULL 值,请始终使用 IS NULL 或 IS NOT NULL 表达式。

    表达式 ... <> NULL、... = NULL、... IN (NULL) 对于所有内容都被评估为 false。

    所以,NULL <> NULL 为假,NUL = NULL 为假。

    【讨论】:

      【解决方案2】:

      尝试作用域:external, where('internal IN (?)', [false,nil])

      【讨论】:

        【解决方案3】:

        试试scope :external, where(:internal => !true)

        【讨论】:

        • !true 将返回 false 并且它将仅返回 internal = false 值而不是空值。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-05
        • 1970-01-01
        • 1970-01-01
        • 2019-01-22
        • 2021-08-18
        • 1970-01-01
        相关资源
        最近更新 更多