Rails 3:范围不正确

发布于 2024-12-09 12:07:26 字数 248 浏览 3 评论 0原文

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

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

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

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

How do I convert the following into something that works on sqlite and mysql? Note, internal is nullable.

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

(In Rails 4, one can simply use:)

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

半边脸i 2024-12-16 12:07:26

ActiveRecord 足够聪明,可以做到这一点,只需执行以下操作:

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

这将用类似的 SQL 进行转换(可能带有表名和队列):

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

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

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

对于

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

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

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

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

ActiveRecord is smart enough for doing this, just do:

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

That would be transformed in similar SQL (with table name and quetes probably):

  • for PostgreSQL and SQLite internal IN ('f') OR internal IS NULL
  • for MySQL internal IN (0) OR internal IS NULL

If need more control you can use Arel:

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

Which would be:

  • for PostgreSQL and SQLite internal = 'f' OR internal IS NULL
  • for MySQL internal = 0 OR internal IS NULL

Remember, if you need to check NULL values in SQL always use IS NULL or IS NOT NULL expressions.

Expresions ... <> NULL, ... = NULL, ... IN (NULL) are evaluated as false for everything.

So, NULL <> NULL is false and NUL = NULL is false.

花开柳相依 2024-12-16 12:07:26

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

Try scope :external, where('internal IN (?)', [false,nil])

攒一口袋星星 2024-12-16 12:07:26

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文