13

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

3 Answers 3

20

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') 
Sign up to request clarification or add additional context in comments.

2 Comments

Can you add the migration file or the schema?
MyModel.where("? = ANY(myarray)", '{42}') should be MyModel.where("? = ANY(myarray)", '42') ? tested on pg 9.6
1

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.

1 Comment

And if it's true try MyModel.where("'?' = ANY(myarray)", 42)
0

seems to had a problem with the name of the array since there was an association with a similar name and rails automagic collided with it

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.