2015-11-13 79 views
2

我不知道如何编写查询。问题:查询Ruby on Rails和PostgreSQL上的数组类型字段

我有两个表,authoritiesnotices每一个与此列:

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

我需要检查,如果从authorities阵列的至少一个元件是notices阵列和保存一个类变量。到目前为止,我已经试过这行代码在我的控制器:

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

我试图在视图中是这样的:

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

编辑

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

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

解决方法是:

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

如这里If array contains value

+0

不存储阵列中的DB。曾经 –

+0

@AndreyDeineko:为什么不呢? SQL支持数组,PostgreSQL支持数组,而Rails4 PostgreSQL接口也如此。这不像他在使用“序列化”的憎恶。 –

+0

@ muistooshort我从来没有试图驳斥它。我只有一些经验,这些经验告诉我,总有(应该是'几乎总是'写成,但在我的情况下总是)更好的方式,即协会。 –

回答

2

说明你可能想使用overlap运营商,而不是containcontain运营商A @> B意味着A包括B的所有元素。如果我明白你想要做什么,你想检查标签数组Notice是否包含任何当前权威的标签。

你可以做到这一点是这样的:

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

这里是Postgres的所有阵列功能的链接: http://postgresql.org/docs/current/static/functions-array.html

+0

谢谢,更新。 – AmitA