samedi 25 avril 2015

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


Aucun commentaire:

Enregistrer un commentaire