在 Ruby on Rails 和 PostgreSQL 上查询数组类型字段

car*_*ñez 6 ruby postgresql ruby-on-rails

我不知道如何编写查询。问题:

我有两张表,authorities每张notices表都有这一列:

t.string "tags",   default:[],   array:true
Run Code Online (Sandbox Code Playgroud)

我需要检查数组中是否至少有一个元素位于authorities数组中notices并将其保存在类变量中。到目前为止,我已经在控制器中尝试了这行代码:

@noticias = Notice.where('tags @> ARRAY[?]',current_authority.tags)
Run Code Online (Sandbox Code Playgroud)

我在视图中尝试了类似的操作:

<% @noticias.each do |notice| %>
    <% notice.nombre %>
<% end %>
Run Code Online (Sandbox Code Playgroud)

编辑

感谢您的回答,但我的问题是

ERROR:  operator does not exist: character varying[] @> text[]
Run Code Online (Sandbox Code Playgroud)

解决办法是:

@noticias = Notice.where('tags && ARRAY[?]::varchar[]',current_authority.tags)
Run Code Online (Sandbox Code Playgroud)

如此处所述如果数组包含值

Ami*_*itA 5

您可能想使用overlap运算符而不是contain。运算containA @> B意味着 A 包含 B 的所有元素。如果我理解你要做什么,你想要检查 的标签数组是否Notice包含当前权限的任何标签。

你可以这样做:

@noticias = Notice.where('tags && ARRAY[?]', current_authority.tags)
Run Code Online (Sandbox Code Playgroud)

以下是 Postgres 中所有数组函数的链接: http ://postgresql.org/docs/current/static/functions-array.html