简体   繁体   English

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

[英]Query for array type field on Ruby on Rails and PostgreSQL

I'm not sure how to do write a query. 我不知道怎么写一个查询。 The issue: 问题:

I have two tables, authorities and notices each one with this column: 我有两个表, authoritiesnotices每个都有这个列:

t.string "tags",   default:[],   array:true

I need to check if at least one element from the authorities array is in the notices array and save it on a class variable. 我需要检查来自authorities数组的至少一个元素是否在notices数组中,并将其保存在类变量中。 So far I've tried this line of code in my controller: 到目前为止,我已经在我的控制器中尝试了这行代码:

@noticias = Notice.where('tags @> ARRAY[?]',current_authority.tags)

I tried something like this in the view: 我在视图中尝试过类似的东西:

<% @noticias.each do |notice| %>
    <% notice.nombre %>
<% end %>

EDIT 编辑

Thanks for you answers but my problem was 谢谢你的答案,但我的问题是

ERROR:  operator does not exist: character varying[] @> text[]

the solution is: 解决方案是:

@noticias = Notice.where('tags && ARRAY[?]::varchar[]',current_authority.tags)

As explained here If array contains value 如此处所述, 如果数组包含值

You probably want to use the overlap operator rather than contain . 您可能希望使用overlap运算符而不是contain The contain operator A @> B means A includes all element of B. If I understand what you're trying to do, you want to check whether the tag array of Notice contains any of the tags of the current authority. contain运算符A @> B表示A包含A @> B所有元素。如果我理解您要执行的操作,则需要检查Notice的标记数组是否包含当前权限的任何标记。

You can do this like this: 你可以这样做:

@noticias = Notice.where('tags && ARRAY[?]', current_authority.tags)

Here is a link on all array functions in Postgres: http://postgresql.org/docs/current/static/functions-array.html 这是Postgres中所有数组函数的链接: http//postgresql.org/docs/current/static/functions-array.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Rails上使用PostgreSQL和Ruby更新数组类型的列 - How to update a column of type array with postgresql and ruby on rails 如何在Ruby on Rails中使用PostgreSQL JSON数组查询ActiveRecord :: Relation - How to use the PostgreSQL JSON array query ActiveRecord::Relation in Ruby on Rails 如何在 Rails 6 上的 Ruby 上正确查询 Postgresql JSONB 哈希数组? - How to properly query Postgresql JSONB array of hashes on Ruby on Rails 6? Rails 4 / Postgresql 9.4-查询和更新数组中的ruby对象 - Rails 4 / postgresql 9.4 - Query and update a ruby object inside an array 在Ruby On Rails / PostgreSQL中按日期对时间戳字段进行分组 - Grouping a timestamp field by date in Ruby On Rails / PostgreSQL 将现有字符串字段类型转换为数据库中的数组字段类型 | 铁轨 + PostgreSQL - Converting existing string field type to array field type in database | Rails + PostgreSQL 如何在 ruby​​ on rails 中查询 Postgresql HSTORE - How to query Postgresql HSTORE in ruby on rails 在 Rails 上的 Ruby 中清空 PostgreSQL 文本数组列 - Emptying a PostgreSQL text array column in Ruby on Rails Ruby on Rails Postgresql数组CSV上传 - Ruby on Rails Postgresql Array CSV upload Ruby / Rails字符串数组到PostgreSQL的插入 - Ruby / Rails array of strings to PostgreSQL insert
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM