使用ActiveRecord在PostgreSQL中匹配数组值

Art*_*Art 5 postgresql activerecord ruby-on-rails

在我的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
Run Code Online (Sandbox Code Playgroud)

控制器中的相关变量:

@contacts_all_user_sorted = Contact.all.where(visible_to: [1]).order("created_at DESC")
Run Code Online (Sandbox Code Playgroud)

d34*_*4n5 5

从这两个网站:

似乎该语法应该起作用:

@contacts_all_user_sorted = Contact.all.where("visible_to @> ARRAY[?]", [1])
Run Code Online (Sandbox Code Playgroud)

它行得通吗?

PS:由于@Quertie在评论中指出的那样,你可能希望在String数组的情况下投出的值,通过更换ARRAY[?]通过ARRAY[?]::varchar[]