【问题标题】:Matching array values in PostgreSQL with ActiveRecord使用 ActiveRecord 匹配 PostgreSQL 中的数组值
【发布时间】:2025-12-19 23:45:07
【问题描述】:

在我的 Rails 4 应用程序中,我的目标是查看所有联系人,其中联系人表中的字段 visible_to 等于 1。我的 visible_to:integer, array: true

但是,我得到以下异常:

PG::UndefinedFunction: ERROR: operator does not exist: integer[] = integer LINE 1: ....* FROM "contacts" WHERE "contacts"."visible_to" IN (1) OR... ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.: SELECT "contacts".* FROM "contacts" WHERE "contacts"."visible_to" IN (1) ORDER BY created_at DESC

我搜索了答案,据我所知,visible_to 类型存在问题。但是,我找不到解决方案。我也尝试从演员表提示中获益,但徒劳无功。

我的迁移:

class AddVisibleToToContacts < ActiveRecord::Migration
    def change
      add_column :contacts, :visible_to, :integer, array: true, default: [], using: 'gin'     
    end 
end

来自控制器的相关变量:

@contacts_all_user_sorted = Contact.all.where(visible_to: [1]).order("created_at DESC")

【问题讨论】:

  • 嗨。您在迁移文件中写“默认”而不是“默认”是否正常?
  • 谢谢,这里只是一个错字。在迁移中一切都很好。
  • 我对问题原因的简短初步汇报。 (1) 一次又一次 RTFM,不仅是 ActiveRecord,还有PostgreSQL (2) 我太依赖类似的问题和similar solution,这与我无关(因为 PostgreSQL 具体的?)。

标签: ruby-on-rails postgresql activerecord


【解决方案1】:

来自这两个网站:

看来这个语法应该可以工作:

@contacts_all_user_sorted = Contact.all.where("visible_to @> ARRAY[?]", [1])

有效吗?

P.S:正如@Quertie 在 cmets 中指出的那样,您可能希望通过将 ARRAY[?] 替换为 ARRAY[?]::varchar[] 来转换字符串数组的值

【讨论】:

  • 这不适用于字符串数组并给出错误ActiveRecord::StatementInvalid: PG::UndefinedFunction: ERROR: operator does not exist: character varying[] @&gt; text[] 。通过将 ARRAY[?] 更改为 ARRAY[?]::varchar[] 来修复它
  • 感谢您的评论@Qwertie。我会在我的答案中添加注释。
【解决方案2】:

您的迁移看起来非常直接且正确。

你可以试试这个吗:

Contact.where('visible_to IN ?', ['1', '2'])

【讨论】:

  • 阿吉特,谢谢帮助。这是来自控制台的结果:Contact Load (0.3ms) SELECT "contacts".* FROM "contacts" WHERE (visible_to IN '1','2') Contact Load (0.3ms) SELECT "contacts".* FROM "contacts" WHERE (visible_to IN '1','2') PG::SyntaxError: ERROR: syntax error at or near "'1'" LINE 1: ... "contacts".* FROM "contacts" WHERE (visible_to IN '1','2') ......
  • P.S.最后的输出错误是output error: #&lt;ActiveRecord::StatementInvalid: PG::SyntaxError: ERROR: syntax error at or near "'1'"
  • 似乎您的 visible_in 列是整数。那是对的吗? \n 请尝试 Contact.where('visible_to in (?)', [1,2])
  • 我也在考虑这个问题,但据我所知,我从手册中了解到我需要在数组中定义一种元素,对吧?我尝试了你的建议,在这种情况下我得到了:output error: #&lt;ActiveRecord::StatementInvalid: PG::UndefinedFunction: ERROR: operator does not exist: integer[] = integer
  • Contact.where(:visible_to => [1,2,3]) 试试这个