[英]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: 我有两个表,
authorities
和notices
每个都有这个列:
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.