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")
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.
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.
From these two websites:
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[]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With