Matching array values in PostgreSQL with ActiveRecord

北城余情 提交于 2019-12-19 19:44:42

问题


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.

However, I get the following exception:

PG::UndefinedFunction: ERROR: operator does not exist: integer[] = integer LINE 1: ....* FROM "contacts" WHERE "contacts"."visible_to" IN (1) OR... ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.: SELECT "contacts".* FROM "contacts" WHERE "contacts"."visible_to" IN (1) ORDER BY created_at DESC

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.

My migration:

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")

回答1:


From these two websites:

  • 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])

Does it work?

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[]




回答2:


your migration seems pretty straight forward and correct.

can you please try this:

Contact.where('visible_to IN ?', ['1', '2'])


来源:https://stackoverflow.com/questions/25202443/matching-array-values-in-postgresql-with-activerecord

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!