使用ActiveRecord在PostgreSQL中匹配数组值

使用ActiveRecord在PostgreSQL中匹配数组值

本文介绍了使用ActiveRecord在PostgreSQL中匹配数组值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Rails 4应用中,我的目标是查看所有联系人,其中联系人表中的字段 visible_to 等于1。我的 visible_to :整数,数组:true

In my Rails 4 app I have a goal to see all contacts, where field visible_to in contacts table equal to 1. My visible_to is :integer, array: true.

但是,出现以下异常:

PG :: UndefinedFunction:错误:运算符不存在:integer [] =整数
第1行:.... * FROM contacts WHERE contacts。 visible_to IN(1)或...
^
提示:没有运算符匹配给定的名称和参数类型。您可能需要添加显式类型强制转换。:SELECT contacts。* FROM contacts WHERE contacts。 visible_to IN(1)ORDER BY created_at DESC

我搜索了答案,据我所知,存在类型为 visible_to 的问题。但是,我找不到解决方案。我也尝试从强制转换提示中受益,但徒劳。

I searched for answers and as far as I see there is an issue with a type of visible_to. However, I couldn't find the solution. I also tried to get benefit from casts hint, but in vain.

我的迁移:

class AddVisibleToToContacts < ActiveRecord::Migration
    def change
      add_column :contacts, :visible_to, :integer, array: true, default: [], using: 'gin'
    end
end

来自控制器的相关变量:

Relevant variable from Controller:

@contacts_all_user_sorted = Contact.all.where(visible_to: [1]).order("created_at DESC")


推荐答案

从这两个网站:




  • http://blog.relatabase.com/rails-postgres-arrays
  • http://adamsanderson.github.io/railsconf_2013/#11

似乎此语法应该起作用:

It seems that this syntax should work:

@contacts_all_user_sorted = Contact.all.where("visible_to @> ARRAY[?]", [1])

能用吗?

P .S:正如@Quertie在评论中指出的那样,对于String数组,您可能希望通过将 ARRAY [?] 替换为<$ c来强制转换值。 $ c> ARRAY [?] :: varchar []

P.S: As @Quertie pointed out in the comments, you may want to cast the value in the case of a String array, by replacing ARRAY[?] by ARRAY[?]::varchar[]

这篇关于使用ActiveRecord在PostgreSQL中匹配数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 06:33