ruby-on-rails - AR 中的 SQL 搜索元素是否不在列数组中

标签 ruby-on-rails postgresql activerecord rails-activerecord

date = Date.today

Subscription.joins(:cart).where("'#{date.beginning_of_week(:sunday).to_s}' != ANY (carts.skipped_weeks)")

购物车上的列 skipped_weeks 是一个日期数组,如 ["2017-04-10", "2017-04-17"]

我正在运行上面的查询并且仍然接收到 cart.skipped_weeks 列数组中包含日期的记录,我只想要 skipped_weeks 数组中不包含该日期的记录。

最佳答案

PostgreSQL 支持 all以及任何:

9.23.4. ALL (array)

expression operator ALL (array expression)

The right-hand side is a parenthesized expression, which must yield an array value. The left-hand expression is evaluated and compared to each element of the array using the given operator, which must yield a Boolean result. The result of ALL is "true" if all comparisons yield true (including the case where the array has zero elements). The result is "false" if any false result is found.

说:

where('? != all(carts.skilled_weeks)', date.beginning_of_week(:sunday))

可能会更符合您的预期逻辑。

关于ruby-on-rails - AR 中的 SQL 搜索元素是否不在列数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43213755/

相关文章:

jquery - 在 Rails 应用程序中输出 JSON

ruby-on-rails - 设计有 'callback' 吗?

sql - PostgreSQL 多列索引连接与比较 ("<"和 ">") 运算符

ruby-on-rails - Rails 5.1 与 ElasticSearch 7.1 重建索引错误

ruby-on-rails - rails : Creating an "All activity feed" from multiple models

ruby-on-rails - 逐行捕获 shell 命令的输出到一个数组中

postgresql - 用yum安装pgadmin3 centos 6

python - 使用第一个元素的值获取结果集中第二个和第三个元素的值

ruby-on-rails - Rails ActiveRecord has_many 通过不工作

ruby-on-rails - 在Ruby on Rails Web应用程序中插入页眉和页脚?