Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying a Postgres array of integers in Rails

my model has a pg array which I use to store integers

Querying using the methods I found from other questions yields errors or gives empty results

MyModel.where("? = ANY (myarray)", 42)

gives

PG::UndefinedFunction: ERROR:  operator does not exist: integer = text

and

 MyModel.where("myarray @> '{?}'", 42)

gives an empty results, yet I do have a model with 42 as one of the ints in the array

#<MyModel:0x007f9a77dd5608> {
                :id => 170,
      :myarray => [
    [0] 42,
    [1] 43,
    [2] 58,
    [3] 61,
    [4] 63
  ]

Is there a special way to query integers(or floats) within a postgres array in Rails?

the migration

class AddMyarrayToMyModel < ActiveRecord::Migration
  def change
    add_column :my_models, :myarray, :integer, array: true, default: []
    add_index  :my_models, :myarray, using: 'gin'
  end
end

and schema

t.integer  "myarray",                 default: [],              array: true
like image 905
Nick Ginanto Avatar asked Apr 25 '15 12:04

Nick Ginanto


2 Answers

Try these:

MyModel.where("? = ANY(myarray)", '{42}')

or

MyModel.where("myarray @> ?", '{42}')

or (on PG 9.6 according to York Yang's comment)

MyModel.where("? = ANY(myarray)", '42') 
like image 99
Sharvy Ahmed Avatar answered Nov 14 '22 04:11

Sharvy Ahmed


PG::UndefinedFunction: ERROR: operator does not exist: integer = text

From this message it appears that the myarray is actually an array of type text. Check that column to make sure it is of the correct type.

like image 1
Wizard of Ogz Avatar answered Nov 14 '22 06:11

Wizard of Ogz