Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matching array values in PostgreSQL with ActiveRecord

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")
like image 882
arthur Avatar asked Aug 08 '14 11:08

arthur


People also ask

Does PostgreSQL support array?

PostgreSQL allows columns of a table to be defined as variable-length multidimensional arrays. Arrays of any built-in or user-defined base type, enum type, composite type, range type, or domain can be created.

How do I declare an array in PostgreSQL?

You can easily create arrays in PostgreSQL by adding square brackets [] immediately after the data type for the column. create table employees ( first_name varchar, last_name varchar, phone_numbers integer[] ); In the above example, we have created column phone_numbers as an array of integers.


1 Answers

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

like image 140
d34n5 Avatar answered Sep 20 '22 02:09

d34n5