Querying a Postgres array of integers in Rails

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

A query using methods that I found from other questions gives 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 empty results, but I have a model with 42 as one of the integers in the array

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

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

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 circuit

t.integer  "myarray",                 default: [],              array: true
+4
source share
3 answers

Try the following:

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

or

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

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

, myarray text. , , .

+1

it seems that there was a problem with the name of the array, since there was an association with the same name, and the automaton of the machine encountered it

0
source

Source: https://habr.com/ru/post/1584624/


All Articles